简体   繁体   中英

R matrix shift by row and replace it with NA

I have the folowing matrix in R .

x <- matrix(1:5,5,5,byrow = T)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    1    2    3    4    5
[3,]    1    2    3    4    5
[4,]    1    2    3    4    5
[5,]    1    2    3    4    5

I would like to create a shifted matrix like below. Basically I would like to increment each row and replace it with NA. For example in Row 2, first value would be NA, and would shift the value by 1. in row 3 first 2 values would be NA and shift the values by 2. I would like to keep the size of the matrix to be constant.

在此处输入图像描述

We can use

x1 <- toeplitz(x[1,])
x1[lower.tri(x1)] <- NA

Or another option is

rbind(x[1,], do.call(rbind, lapply(2:nrow(x), 
       function(i) c(rep(NA, i-1), head(x[i,], -i+1)))))
#      [,1] [,2] [,3] [,4] [,5]
#[1,]    1    2    3    4    5
#[2,]   NA    1    2    3    4
#[3,]   NA   NA    1    2    3
#[4,]   NA   NA   NA    1    2
#[5,]   NA   NA   NA   NA    1

You could also use for ,

(this now cleaned up based on @Shree 's suggestion):

for (i in 2:nrow(x)) x[i, ] <- c(rep(NA, (i-1)), x[i, ])[1:ncol(x)]

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