Lime
Lime

Reputation: 756

sequence to drop multiple raster layers

I'm trying to drop multiple raster layers by using the function dropLayers combined with rep, although, when I used this code:

x <- c(1:4, 10:12)
s <- dropLayer(p, rep(x, 10))

names(s)
  [1] "y2010.5"  "y2010.6"  "y2010.7"  "y2010.8"  "y2010.9" 
  [6] "y2011.1"  "y2011.2"  "y2011.3"  "y2011.4"  "y2011.5" 
 [11] "y2011.6"  "y2011.7"  "y2011.8"  "y2011.9"  "y2011.10"
 [16] "y2011.11" "y2011.12" "y2012.1"  "y2012.2"  "y2012.3" 
 [21] "y2012.4"  "y2012.5"  "y2012.6"  "y2012.7"  "y2012.8" 
 [26] "y2012.9"  "y2012.10" "y2012.11" "y2012.12" "y2013.1" 
 [31] "y2013.2"  "y2013.3"  "y2013.4"  "y2013.5"  "y2013.6" 
 [36] "y2013.7"  "y2013.8"  "y2013.9"  "y2013.10" "y2013.11"
 [41] "y2013.12" "y2014.1"  "y2014.2"  "y2014.3"  "y2014.4" 
 [46] "y2014.5"  "y2014.6"  "y2014.7"  "y2014.8"  "y2014.9" 
 [51] "y2014.10" "y2014.11" "y2014.12" "y2015.1"  "y2015.2" 
 [56] "y2015.3"  "y2015.4"  "y2015.5"  "y2015.6"  "y2015.7" 
 [61] "y2015.8"  "y2015.9"  "y2015.10" "y2015.11" "y2015.12"
 [66] "y2016.1"  "y2016.2"  "y2016.3"  "y2016.4"  "y2016.5" 
 [71] "y2016.6"  "y2016.7"  "y2016.8"  "y2016.9"  "y2016.10"
 [76] "y2016.11" "y2016.12" "y2017.1"  "y2017.2"  "y2017.3" 
 [81] "y2017.4"  "y2017.5"  "y2017.6"  "y2017.7"  "y2017.8" 
 [86] "y2017.9"  "y2017.10" "y2017.11" "y2017.12" "y2018.1" 
 [91] "y2018.2"  "y2018.3"  "y2018.4"  "y2018.5"  "y2018.6" 
 [96] "y2018.7"  "y2018.8"  "y2018.9"  "y2018.10" "y2018.11"
[101] "y2018.12" "y2019.1"  "y2019.2"  "y2019.3"  "y2019.4" 
[106] "y2019.5"  "y2019.6"  "y2019.7"  "y2019.8"  "y2019.9" 
[111] "y2019.10" "y2019.11" "y2019.12"

Only the first four, and the last three are dropped for the first layer. Every other layer after that is not affected. How can I make this work? I have tried sequence, but did not manage to work it out.

Upvotes: 0

Views: 274

Answers (1)

drJones
drJones

Reputation: 1233

I assume you want to remove all rasters ending in 1-4 or 10-12 after the period. The code you are using instead tries to remove rasters 1:4 and 10:12 ten times. You can use this code which isolates the numeral after the period using sub and checks if this numeral is in x using the %in% operator:

s <- dropLayer(p, sub('.*\\.', '', names(p)) %in% x)

Upvotes: 0

Related Questions