[英]for loop to stack rasters stored in different lists in R
我有一个嵌套列表,其中包含许多元素和每个元素内的 x 个栅格。 列表的简化结构如下所示:
## create main List
r <- raster(ncol=3, nrow=3)
values(r) <- 1:ncell(r)
s <- stack(r,r*2,r*3)
List <- split(as.list(s), 1) # here List has a single element but in the real example has >10
我需要将存储在另一个列表(名为 Ref_List)中的栅格堆叠到存储在主列表中的栅格,相应地:
stack(List[[1]][[1]], Ref_list[[1]])
stack(List[[1]][[2]], Ref_list[[2]])
stack(List[[1]][[3]], Ref_list[[3]])
...
Ref_list[[i]]
中包含的栅格数与List[[i]][[j]]
中包含的栅格数相同。 我尝试了以下循环来执行堆栈操作,但结果是 NULL。
关于如何解决这个问题的任何想法? 谢谢!
List_stack <- lapply(List,function(i){ # i specifies elements within the list
lapply(i,function(j){ # j specifies the elements of each element, within the list
st <- stack(j)
## create REF list
z <- raster(ncol=3, nrow=3)
values(z) <- 0.5:ncell(z)
t <- stack(z,z*2,z*3)
Ref_list <- as.list(t)
## STACK REF list with MainList
for(i in 1:length(Ref_list)){
final <- stack(Ref_list[[i]], st)
}
})
})
我猜你需要退货? 而且我认为堆叠的部分是错误的..您正在用每次迭代替换final
List_stack <- lapply(List,function(i){ # i specifies elements within the list
lapply(i,function(j){
# j specifies the
#elements of each element, within the list
st <- stack(j)
## create REF list
z <- raster(ncol=3, nrow=3)
values(z) <- 0.5:ncell(z)
t <- stack(z,z*2,z*3)
Ref_list <- as.list(t)
# i think you need to do this
final = do.call(stack,list(Ref_list,st))
return(final)
})
})
这个怎么样? 基本上我所做的是将j
固定为1
并将i
固定为List[[1]]
的长度。
list_stack <- list() # There is a better way to initialize a list
for(i in 1:length(List[[1]])){
for(j in seq_along(List)){
list_stack[[i]] <- stack(List[[j]][[i]], Ref_list[[i]])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.