有没有一种方法可以简化/循环栅格堆栈子集?

时间:2019-04-17 07:06:15

标签: r

我正在尝试简化我的代码。我有一个“堆叠”有194个栅格图层的栅格堆栈。我想像下面这样子化它。有更简单的方法可以做到这一点吗?

stacked <- stack(example)

yr1 <- subset(stacked, 1:6)
yr2 <- subset(stacked, 7:18)
yr3 <- subset(stacked, 19:30)
yr4 <- subset(stacked, 31:42)
yr5 <- subset(stacked, 43:54)
yr6 <- subset(stacked, 55:66)
yr7 <- subset(stacked, 67:78)
yr8 <- subset(stacked, 79:90)
yr9 <- subset(stacked, 91:102)
yr10 <- subset(stacked, 103:114)
yr11 <- subset(stacked, 115:126)
yr12 <- subset(stacked, 127:138)
yr13 <- subset(stacked, 139:150)
yr14 <- subset(stacked, 151:162)
yr15 <- subset(stacked, 163:174)
yr16 <- subset(stacked, 175:186)
yr17 <- subset(stacked, 187:194)

我希望有17个新的栅格堆栈,每个堆栈都包含上面指示的栅格图层。

3 个答案:

答案 0 :(得分:2)

如果,班级间隔不一致,并且您需要定义间隔,那么一种方法如下:

library(raster)

#reproducible example
set.seed(987)

# setting up example raster stack
r1 <- raster(nrows = 1, ncols = 1, res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = runif(36, 1, 5))
r.stack <- stack(lapply(1:20, function(i) setValues(r1,runif(ncell(r1)))))

#solution using a list
out <- list()
for (i in 1:5) {
  intervals <- c(1,4,7,11,16,21)
  s <- c(intervals[[i]]:intervals[[i+1]])
  out[[i]] <- subset(r.stack,s[1:length(s)-1]) #remove the last one as it doesnt belong to the class
}

答案 1 :(得分:1)

由于您的休息时间似乎有规律的间隔,我们可以用seq定义它们并添加特殊情况:

breaks <- data.frame(lower=c(1,seq(7,175,12),187),upper=c(6,seq(18,186,12),194))
years <- lapply(1:nrow(breaks),function(x){return(subset(stacked,breaks[x,'lower']:breaks[x,'upper']))})
names(years) <- paste0("yr",1:nrow(breaks))

答案 2 :(得分:0)

拥有17个RasterStack对象,可能不是您应该做的事情,是相当笨拙的(但是如果有的话,将它们放在列表中,例如Majid和Julian_Hn显示)。我不知道您应该做什么,因为没有上下文,但是您可以创建一个这样的矩阵

yrs <- matrix( c(1,6,7,18,19,30,31,42,43,54,55,66,67,78,79,90,91,102,103,114,115,
            126,127,138,139,150,151,162,163,174,175,186,187,194), ncol=2, byrow=T)

然后在需要时提取所需的年份

yr10 <- stacked[[ yrs[10,1]:yrs[10,2] ]]

yr10 <- subset(stacked, yrs[10,1], yrs[10,2])