Rachel
Rachel

Reputation: 129

Is there a way to simplify/loop raster stack subsetting?

I am trying to simplify my code. I have a raster stack "stacked" with 194 raster layers. I would like to subset it like below. Is there an easier way to accomplish this?

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)

I expect to have 17 new raster stacks each containing the raster layers indicated above.

Upvotes: 0

Views: 160

Answers (3)

Robert Hijmans
Robert Hijmans

Reputation: 47536

it is rather unwieldy to have 17 RasterStack objects, and probably not what you should be doing (but if you do, put them in a list, like Majid and Julian_Hn show). I do not know what you should do, as there is no context, but you could make a matrix like this

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)

And then extract the year you want when needed

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

or

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

Upvotes: 0

Majid
Majid

Reputation: 1854

If the class intervals are not consistent and you need to define the intervals then one way to do this is as below:

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
}

Upvotes: 2

Julian_Hn
Julian_Hn

Reputation: 2141

Since your breaks seem to be somewhat regularly spaced we could define them with seq and add the special cases:

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))

Upvotes: 1

Related Questions