简体   繁体   English

申请家族中的两个列表

[英]Two lists in apply family

I am trying to extract two regions ex1 and ex2 (in exlist ) from a list of rasters ( rasterlist ) using the apply family and extract from the raster package.我正在尝试使用apply系列从栅格列表( rasterlist )中提取两个区域ex1ex2 (在exlist )并从栅格包中extract I could use a nested for loop but was wondering if there is a way to achieve this in with one of the apply family members, since nested for loops are considered more or less bad practice in R .我可以使用嵌套的 for 循环,但想知道是否有一种方法可以使用 apply 家族成员之一来实现这一点,因为嵌套的 for 循环在 R 中或多或少被认为是不好的做法 Here the dummy code:这里是虚拟代码:

library(raster)
ras1 <- raster(matrix(runif(20), nrow = 5, ncol = 5))
ras2 <- ras1 * 2
ras3 <- ras1 * 0.5
rasterlist <- list(ras1, ras2, ras3)
ex1 <- extent(0, 0.4, 0, 0.4)
ex2 <- extent(0.6, 1, 0.4, 1)
exlist <- list(ex1, ex2)

At the moment I've got this as a (rather unsatisfying) solution:目前,我将此作为(相当不满意的)解决方案:

out1 <- lapply(rasterlist, function(i) extract(i, ex1))
out2 <- lapply(rasterlist, function(i) extract(i, ex2))

NB The solution it does not need to be a member of the apply family (although that was the task I set myself) if there is a better, faster, more elegant way please share.注:该解决方案并不需要是申请家庭成员(虽然这是我给自己定下任务)如果有一个更好,更快,更优雅的方式,请分享。

You could start with combining the regions into a single SpatialPolygons object (maybe they are to begin with?).您可以从将这些区域组合成一个 SpatialPolygons 对象开始(也许它们是从开始的?)。 With your example data that can be done like this:使用可以像这样完成的示例数据:

ex <- do.call(bind, sapply(exlist, function(x) as(x, 'SpatialPolygons')))

In this example (with RasterLayer objects that can be stacked) you can then do在此示例中(使用可以堆叠的 RasterLayer 对象),您可以执行以下操作

s <- stack(rasterlist)
extract(s, ex)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM