三维数组列表 [英] Three dimensional array to list
问题描述
我的问题可能听起来微不足道的相当多的你,但长时间上网搜索后我还没有回答以下问题:
如何将一个三维数组转换成三维名单?
假如我有以下内容:
A1中 - 基质(runif(12),4,3)
A2&下; - 基质(runif(12),4,3)
A3&下; - 基质(runif(12),4,3)MYLIST< - 表(A1,A2,A3)MYARRAY< - 阵列(NA,C(4,3,3))
MYARRAY [,, 1]; - A1
MYARRAY [,, 2]< - A2
MYARRAY [,, 3]< - A3
有没有一种方法来转换 MYARRAY
与同一结构 MYLIST
?名单p>
非常感谢您的帮助!
最好,罗曼
为了好玩(因为我迟到了),这里是另外一个仅使用基地R.像@ joran的,它是可编程的,在这个意义上,你可以很容易地沿任意给定尺寸分裂 N
:
split.along.dim< - 功能(A,N)
setNames(lapply(分(一,arrayInd(seq_along(一),暗(A))中,n]),
阵列,昏暗朦胧=(一)[ - N],dimnames(一)[ - N]),
dimnames(一)[[N]])相同的(split.along.dim(MYARRAY,N = 3),MYLIST)
#[1] TRUE
这也将preserve所有dimnames如果您有任何见例如:
dimnames(MYARRAY)LT; - 地图(paste0,字母[seq_along(变暗(MYARRAY))]
lapply(点心(MYARRAY),SEQ))
split.along.dim(MYARRAY,N = 3)
my question might sound trivial to quite a lot of you, but after a long internet search I still don't have an answer to the following question:
How to convert a three dimensional array to a "three dimensional" list?
Suppose I have the following:
A1 <- matrix(runif(12),4,3)
A2 <- matrix(runif(12),4,3)
A3 <- matrix(runif(12),4,3)
MyList <- list(A1,A2,A3)
MyArray <- array(NA,c(4,3,3))
MyArray[,,1] <- A1
MyArray[,,2] <- A2
MyArray[,,3] <- A3
Is there a way to convert MyArray
into a list with "the same structure" as MyList
?
Thank you very much for your help! Best, Romain
For fun (since I'm late), here is another one that only uses base R. Like @joran's, it is programmable in the sense you can easily split along any given dimension n
:
split.along.dim <- function(a, n)
setNames(lapply(split(a, arrayInd(seq_along(a), dim(a))[, n]),
array, dim = dim(a)[-n], dimnames(a)[-n]),
dimnames(a)[[n]])
identical(split.along.dim(MyArray, n = 3), MyList)
# [1] TRUE
It will also preserve all your dimnames if you have any, see for example:
dimnames(MyArray) <- Map(paste0, letters[seq_along(dim(MyArray))],
lapply(dim(MyArray), seq))
split.along.dim(MyArray, n = 3)
这篇关于三维数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!