假设我有一个矩阵列表:
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我想逆转这个过程,从list中得到矩阵的long.matrix。
我可以用for循环手动完成它,但是我正在搜索类似于:我认为应该存在的function(long.matrix, 3)。有这样的事吗?
发布于 2016-06-20 23:41:35
蛮力解决方案:
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 4rep为split构建类别,以拆分数据。因为R是列-专业,这里我们取前四个,第二个四个,第三个四个条目。
在您的示例long.matrix和3的当前维度的值中,该函数简化为:
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以获得所需的格式。
发布于 2016-06-20 23:46:05
这样做:
listm=list() #i=1
for(i in 1:3)listm[[i]]=long.matrix[,(2*i-1):(i*2)]版本
lapply(1:3,function(ii)long.matrix[,(2*ii-1):(ii*2)])
[[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发布于 2016-06-21 07:48:19
为此,我更喜欢使用数组维度。然后,可以为矩阵定义一个split方法:
split.matrix <- function(x, rslice = 1, cslice = 1) {
if (ncol(x) %% cslice) stop("cslice not divisor of number of columns")
if (nrow(x) %% rslice) stop("rslice not divisor of number of rows")
x <- t(x)
dim(x) <- c(dim(x)[1],
dim(x)[2] / rslice,
rslice)
x <- lapply(seq_len(rslice), function(k, a) t(a[,,k]), a = x)
if (cslice > 1) {
x <- lapply(x, function(y, k) {
dim(y) <- c(dim(y)[1],
dim(y)[2] / k,
k)
y <- lapply(seq_len(k), function(k, a) a[,,k], a = y)
y
}, k = cslice)
}
if(length(x) == 1L) x <- x[[1]]
x
}
split(long.matrix, 1, 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
split(long.matrix, 1, 1)
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 1 3 1 3 1 3
#[2,] 2 4 2 4 2 4
split(long.matrix, 2, 1)
#[[1]]
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 1 3 1 3 1 3
#
#[[2]]
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 2 4 2 4 2 4
split(long.matrix, 2, 3)
#[[1]]
#[[1]][[1]]
#[1] 1 3
#
#[[1]][[2]]
#[1] 1 3
#
#[[1]][[3]]
#[1] 1 3
#
#
#[[2]]
#[[2]][[1]]
#[1] 2 4
#
#[[2]][[2]]
#[1] 2 4
#
#[[2]][[3]]
#[1] 2 4https://stackoverflow.com/questions/37933357
复制相似问题