[英]Extract multiple values from raster using for loop
I'm trying to extract multiple cell values from a raster using the following for-loop:我正在尝试使用以下 for 循环从栅格中提取多个单元格值:
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
h(simpleError(msg, call)) 中的错误:在为 function 'extract' 选择方法时评估参数 'y' 时出错:维数不正确
In general use example data (see?stack).通常使用示例数据(参见?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:发生错误是因为您迭代了一维的字符向量(
paste0("y",2011:2019
),并且您尝试像二维的 data.frame i[,1:2]
一样对其进行子集化。但是, raster::extract()
的第二个元素应该是:
points represented by a two-column matrix or data.frame, or SpatialPoints*;
由两列矩阵或 data.frame 或 SpatialPoints* 表示的点; SpatialPolygons*;
空间多边形*; SpatialLines;
空间线; sf spatial vector objects;
sf 空间矢量对象; 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.如果由于堆栈尺寸或点(或多边形)的数量而导致值提取的计算量很大,那么exactextractr package中有一个很棒的
exactextractr
exact_extract()
,它比raster::extract()
快得多,并且具有或多或少的相同争论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.