简体   繁体   中英

How use sapply() to construct this matrix difference operator in R

If the question is how to produce the matrix shown in the image that appears when you click on the text in the question then here are several ways:

diff(diag(4))
##      [,1] [,2] [,3] [,4]
## [1,]   -1    1    0    0
## [2,]    0   -1    1    0
## [3,]    0    0   -1    1

apply(diag(4), 1, diff)
##      [,1] [,2] [,3] [,4]
## [1,]   -1    1    0    0
## [2,]    0   -1    1    0
## [3,]    0    0   -1    1

sapply(as.data.frame(diag(4)), diff)
##      V1 V2 V3 V4
## [1,] -1  1  0  0
## [2,]  0 -1  1  0
## [3,]  0  0 -1  1

sapply(1:4, function(i) diff(diag(4)[, i]))
##      [,1] [,2] [,3] [,4]
## [1,]   -1    1    0    0
## [2,]    0   -1    1    0
## [3,]    0    0   -1    1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM