Reputation: 756
I'm trying to extract multiple cell values from a raster using the following for-loop:
testis <- NULL
for(i in paste0("y", 2011:2019)){
testis[i] <- raster::extract(rf[[c(1, 3)]], i[, 1:2])
}
In replacement for:
e_change <- raster::extract(rf[[c(1, 3)]], y2019[, 1:2]) #extract cell values
Although, I get the following error:
Error in h(simpleError(msg, call)) : error in evaluating the argument 'y' in selecting a method for function 'extract': incorrect number of dimensions
Upvotes: 0
Views: 925
Reputation: 2584
In general use example data (see ?stack).
the error occurs because you iterate over a character vector (paste0("y",2011:2019
) that is one-dimensional and you try to subset it like data.frame i[,1:2]
which is two-dimensional.
However, the second element of raster::extract()
should be:
points represented by a two-column matrix or data.frame, or SpatialPoints*; SpatialPolygons*; SpatialLines; sf spatial vector objects; Extent; or a numeric vector representing cell numbers
so you can't extract anything from a character vector. you can extract value with cells number or points location, which would seem what you want to do
r <- raster(ncol=36, nrow=18, vals=1:(18*36))
s <- stack(r,r*2,r/3)
#extract with cell number
raster::extract(s[[c(1, 3)]],c(1:100),df=T)
#extract with points
xy <- cbind(-50, seq(-80, 80, by=20))
raster::extract(s[[c(1, 3)]],xy,df=T)
sp <- SpatialPoints(xy)
raster::extract(s[[c(1, 3)]],sp,df=T)
Just a note for the speed issue. If values extraction is computationally intense due to the stack dimension or the number of points (or polygon), there is a wonderful function exact_extract()
from exactextractr
package that is waaaaay faster than raster::extract()
and have more or less the same argument.
Upvotes: 0