当我将矢量转换为具有填充矩阵的元素太少的矩阵时,矢量的元素将被回收。有没有什么方法可以用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]
我希望得到的矩阵是
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[4,] 7 8
[5,] 9 10
[6,] 11 NA
答案 0 :(得分: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
答案 1 :(得分:2)
这将创建一个矩阵,其中包含nr
行的x
行,末尾有NA,而没有任何警告。
# inputs
nr <- 2
x <- 1:11
nc <- ceiling(length(x) / nr)
,然后执行以下任意操作:
t(replace(matrix(NA, nc, nr), seq_along(x), x))
matrix(`length<-`(x, nr * nc), nr, byrow = TRUE)
matrix(c(x, rep(NA, nr * nc - length(x))), nr, byrow = TRUE)
matrix(replace(rep(NA, nr * nc), seq_along(x), x), nr, byrow = TRUE)
要按列填充矩阵,请使用它代替第一个替代方案,并为其余替代方案省略byrow=TRUE
。
replace(matrix(NA, nr, nc), seq_along(x), x)