假设我有这个数组:
my.array <- array(1:48, dim=c(3,4,4))
在做了一些尴尬的转换后,我最终得到了以下数据:
tarray <- apply(my.array, c(1,3), t)
listarray <-apply(tarray, 3, as.list)
ulist <- lapply(listarray, unlist)
trlist <- lapply(ulist, t)
[[1]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 4 7 10 2 5 8 11 3 6
[,11] [,12]
[1,] 9 12
[[2]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 13 16 19 22 14 17 20 23 15 18
[,11] [,12]
[1,] 21 24
[[3]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 25 28 31 34 26 29 32 35 27 30
[,11] [,12]
[1,] 33 36
[[4]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 37 40 43 46 38 41 44 47 39 42
[,11] [,12]
[1,] 45 48
我想保存它,以便每个列表项都有自己的行,即
1 4 7 10 2 5 8 11 3 6 9 12
13 16 19 22 14 17 20 23 15 18 21 24
25 28 31 34 26 29 32 35 27 30 33 36
37 40 43 46 38 41 44 47 39 42 45 48
但是当我使用write.table(trlist, file="test", sep="/t", row.names=FALSE,col.names = FALSE, quote = FALSE)
时,它只会将所有内容保存在一行
答案 0 :(得分:3)
我们可以通过循环第三维来提取“我的。沿着该维度,转置,连接到vector
并通过rbind
list
元素将其转换为单个矩阵
do.call(rbind, lapply(seq(dim(my.array)[3]), function(i) c(t(my.array[,,i]))))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
#[1,] 1 4 7 10 2 5 8 11 3 6 9 12
#[2,] 13 16 19 22 14 17 20 23 15 18 21 24
#[3,] 25 28 31 34 26 29 32 35 27 30 33 36
#[4,] 37 40 43 46 38 41 44 47 39 42 45 48
或者另一种方法是使用aperm
,然后将其转换为matrix
matrix(c(aperm(my.array, c(2, 1, 3))), nrow = 4, byrow = TRUE)