Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

r - Three dimensional array to list

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use lapply:

lapply(seq(dim(MyArray)[3]), function(x) MyArray[ , , x])


# [[1]]
#           [,1]       [,2]      [,3]
# [1,] 0.2050745 0.21410846 0.2433970
# [2,] 0.9662453 0.93294504 0.1466763
# [3,] 0.5775559 0.86977616 0.6950287
# [4,] 0.4626039 0.04009952 0.5197830
# 
# [[2]]
#           [,1]      [,2]      [,3]
# [1,] 0.6323070 0.2684788 0.7232186
# [2,] 0.1986486 0.2096121 0.2878846
# [3,] 0.3064698 0.7326781 0.8339690
# [4,] 0.3068035 0.4559094 0.8783581
# 
# [[3]]
#           [,1]      [,2]      [,3]
# [1,] 0.9557156 0.9069851 0.3415961
# [2,] 0.5287296 0.6292590 0.8291184
# [3,] 0.4023539 0.8106378 0.4257489
# [4,] 0.7199638 0.2708597 0.6327383

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...