gpt4 book ai didi

r - 逆 cbind() 函数 R

转载 作者:行者123 更新时间:2023-12-04 19:51:01 25 4
gpt4 key购买 nike

假设我有一个矩阵列表:

matrix <- matrix(1:4, nrow = 2, ncol = 2)
list <- list(matrix, matrix, matrix)

还有一个由函数cbind()创建的矩阵:

long.matrix <- do.call(cbind, list)

[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 3 1 3 1 3
[2,] 2 4 2 4 2 4

我想反转过程以从 long.matrix 中获取矩阵的 list

我可以使用 for 循环手动完成,但我正在寻找类似的东西: function(long.matrix, 3) 我认为应该存在。有这种事吗?

最佳答案

暴力破解:

f <- function(long.matrix, num)
lapply(split(long.matrix,
rep(seq(num), each=(ncol(long.matrix)/num)*nrow(long.matrix))),
function(x) matrix(x, nrow=nrow(long.matrix))
)

f(long.matrix, 3)
## $`1`
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
##
## $`2`
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
##
## $`3`
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4

repsplit 构建类别,以拆分数据。由于 R 是列优先的,这里我们取前四个、第二个四个、第三个四个条目。

填写示例 long.matrix3 的当前维度的值,函数简化为:

lapply(split(long.matrix, rep(seq(3), each=4)), function(x) matrix(x, nrow=2))

注意:

(r <- rep(seq(3), each=4) )
## [1] 1 1 1 1 2 2 2 2 3 3 3 3
split(long.matrix, r)
## $`1`
## [1] 1 2 3 4
##
## $`2`
## [1] 1 2 3 4
##
## $`3`
## [1] 1 2 3 4

然后将其中的每一个传递给 matrix 以获得所需的格式。

关于r - 逆 cbind() 函数 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37933357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com