考虑下面的代码来创建一个矩阵x
:
x = matrix(1:18, nrow=6, byrow=T)
x
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[4,] 10 11 12
[5,] 13 14 15
[6,] 16 17 18
现在我希望将x
转换为一个新的矩阵x1
,其中x的每两行作为一个新矩阵,进行转置,最后所有转置矩阵都被合并。这可以通过以下代码来完成:
x1 = c()
for (i in 1:(nrow(X)/2)) x1 = rbind(x1, t(x[((i-1)*2+1):(i*2),]))
x1
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
[4,] 7 10
[5,] 8 11
[6,] 9 12
[7,] 13 16
[8,] 14 17
[9,] 15 18
我想知道这是否可以由 apply
家族的成员来完成,因为在我的例子中 x
非常大并且使用 for
循环需要很长时间才能执行。我还想知道是否还有其他快速代码可以实现此转换。
编辑:我的 x
有 1770000
行和 12
列。行数是 590 的乘积,因此生成的矩阵 x1
应包含 36000
行和 590
列。我尝试将@akrun代码调整为:
x1 = do.call(rbind, lapply(split(x, (seq_len(nrow(x))-1) %/% 590),
matrix, ncol=590, byrow = TRUE))
但我收到警告:
In FUN(X[[i]], ...) :
data length [12] is not a sub-multiple or multiple of the number of columns [590]
此外,x1
类似于:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590
[2,] Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590
[3,] Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590
最佳答案
我们可以使用 split
rbind
方法,这样会更快
do.call(rbind, lapply(split(x, (seq_len(nrow(x))-1) %/% 2), matrix, ncol=2, byrow = TRUE))
基准
x <- matrix(1:180000, nrow = 60000, byrow = TRUE)
system.time({
x1 = c()
for (i in 1:(nrow(x)/2)) x1 = rbind(x1, t(x[((i-1)*2+1):(i*2),]))
})
# user system elapsed
# 6.78 0.56 7.39
system.time({
x2 <- do.call(rbind, lapply(split(x, (seq_len(nrow(x))-1) %/% 2),
matrix, ncol=2, byrow = TRUE))
})
# user system elapsed
# 0.24 0.00 0.23
identical(x1, x2)
#[1] TRUE
关于r - 矩阵变换的快速方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47251051/