无需回收即可将矢量转换为矩阵

Dav*_*son 4 r vector matrix

当我将矢量转换为具有太少元素以填充矩阵的矩阵时,矢量的元素被回收.有没有办法将回收利用或用NA取代回收的元素?

这是默认行为:

> matrix(c(1,2,3,4,5,6,7,8,9,10,11),ncol=2,byrow=TRUE)
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6
[4,]    7    8
[5,]    9   10
[6,]   11    1
Warning message:
In matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), ncol = 2, byrow = TRUE) :
  data length [11] is not a sub-multiple or multiple of the number of rows [6]
Run Code Online (Sandbox Code Playgroud)

我希望得到的矩阵是

     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6
[4,]    7    8
[5,]    9   10
[6,]   11   NA
Run Code Online (Sandbox Code Playgroud)

Ric*_*ven 9

您无法关闭回收,但在形成矩阵之前,您可以对向量进行一些操作.我们可以根据矩阵的尺寸来扩展矢量的长度.的length<-替换功能将垫用该载体NA达到所需长度.

x <- 1:11
length(x) <- prod(dim(matrix(x, ncol = 2)))
## you will get a warning here unless suppressWarnings() is used
matrix(x, ncol = 2, byrow = TRUE)
#      [,1] [,2]
# [1,]    1    2
# [2,]    3    4
# [3,]    5    6
# [4,]    7    8
# [5,]    9   10
# [6,]   11   NA
Run Code Online (Sandbox Code Playgroud)