从向量创建矩阵,所有向量元素向下移动2步

时间:2016-03-06 17:04:15

标签: r

说我有

v = rbind(1, 1, 0, 0, 0, 0)
# > v
# [,1]
# [1,]    1
# [2,]    1
# [3,]    0
# [4,]    0
# [5,]    0
# [6,]    0

我怎么做到这一点?

# > m
#       [,1]  [,2]  [,3]
# [1,]    1     0     0
# [2,]    1     0     0
# [3,]    0     1     0 
# [4,]    0     1     0
# [5,]    0     0     1
# [6,]    0     0     1

1 个答案:

答案 0 :(得分:5)

您可以添加两个零并回收矢量:

v1 <- c(v,0,0)
m <- matrix(v1,ncol=3,nrow=6)

(忽略警告)

> m
#     [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    1    0    0
#[3,]    0    1    0
#[4,]    0    1    0
#[5,]    0    0    1
#[6,]    0    0    1