首页 > 解决方案 > 在 R 中使用循环从列表中填充数组

问题描述

我在 R 中有一个列表,其中包含逐月逐层的叶面积值,就像这样

ls <- list(month = c(1,1,2,2,3,3,4,4),
           layer = c(0,1,0,1,0,1,0,1),
           LA = c(runif(8)))

我想创建一个数组,每个月按层显示 LA 的快照,第 0 层对应于数组中每个矩阵的底部,第 1 层对应于顶部。我创建了一个数组

canopy <- array(dim = c(2,1,4))

并试图用 for 循环填充它

for (i in 1:4) {
  if (ls$month == i){
    if (ls$layer == 0){
       canopy[2,1,i] <-  ls$LA
    } else if (ls$layer == 1){
       canopy[1,1,i] <-  ls$LA
    }}}

但是,这会产生错误

Error in canopy[2, 1, i] <- ls$LA : 
  number of items to replace is not a multiple of replacement length
In addition: Warning messages:
1: In if (ls$month == i) { :
  the condition has length > 1 and only the first element will be used
2: In if (ls$layer == 0) { :
  the condition has length > 1 and only the first element will be used

我怎样才能清理这个?

标签: rarrayslistfor-loopif-statement

解决方案


将数据放入 3 维矩阵总是很棘手。确保这确实是您所需要的。对于此示例,标准矩阵/数据框可能是更好的解决方案。

在这个解决方案中,我遍历月数并确定每个月的向量索引,然后从列表的每个向量中提取这些元素。棘手的部分之一是图层为 0 或 1。R 中没有 0 索引(Python 是的),因此我在图层中添加了一个以将其正确放置在矩阵中。

试试这个:

ls <- list(month = c(1,1,2,2,3,3,4,4),
           layer = c(0,1,0,1,0,1,0,1),
           LA = c(runif(8)))

canopy <- array(dim = c(2,1,4))
#Rows are layer
#Columns are LA
#Matrixes are month

for (i in 1:4) {
  month <- which(ls$month ==i)
  canopy[ls$layer[month]+1, ,i] <-ls$LA[month]
   
}
canopy

, , 1

[,1]
[1,] 0.1941003
[2,] 0.5879553

, , 2

[,1]
[1,] 0.8284857
[2,] 0.7242819

, , 3

[,1]
[1,] 0.8078793
[2,] 0.3489988

, , 4

[,1]
[1,] 0.25424950
[2,] 0.05117571

推荐阅读