简体   繁体   English

如何在 raster::extract() 中传递多个函数

[英]How to pass multiple function in raster::extract()

I'm working with a raster CHM and I've to extract several metrics from a polygon shapefile.我正在使用栅格 CHM,我必须从多边形 shapefile 中提取几个指标。 Now I'm doing something like this:现在我正在做这样的事情:

library(raster)
library(sp)

#from the help page of extract
r <- raster(ncol=36, nrow=18, vals=1:(18*36))
cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0))
polys <- spPolygons(cds1, cds2)

#metrics extraction
mean <- extract(r, polys,mean,df=T)
min<-extract(r, polys,min,df=T)
max<-extract(r, polys,max,df=T)
#and so on for other summary functions (like sd, mode, median, sum etc...)

I would know if there is a way to pass all the summary functions to the fun= argument of the extract() function and if it's possible to do it in parallel.我想知道是否有办法将所有汇总函数传递给 extract() 函数的 fun= 参数,以及是否可以并行执行。 Thanks for every help.感谢您的帮助。

NB this is my first question in StackOverflow, I apologize for any impropriety注意这是我在 StackOverflow 中的第一个问题,对于任何不当行为我深表歉意

As @dww suggests above in the comments, here is a function which calculates a number of summary statistics and returns them as a vector.正如@dww 在上面的评论中所建议的那样,这里有一个函数可以计算一些汇总统计数据并将它们作为向量返回。 It is passed to the fun argument of raster::extract .它被传递给raster::extractfun参数。 Note that the documentation from raster::extract says that the function must accept a na.rm argument.请注意,来自raster::extract的文档说该函数必须接受na.rm参数。 I was unable to change the default behavior of extract for naming the columns of the data frame output so I manually set the names afterward.我无法更改extract命名数据框输出列的默认行为,因此我随后手动设置了名称。

Code代码

my_summary <- function(x, na.rm) c(mean = mean(x, na.rm=na.rm), min = min(x, na.rm=na.rm), max = max(x, na.rm=na.rm))
r_summary <- extract(r, polys, fun = my_summary, df = TRUE)
names(r_summary) <- c('ID', 'mean', 'min', 'max')

Output输出

  ID     mean min max
1  1 387.8158 326 507
2  2 321.0800 172 498

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM