如何在raster :: extract()中传递多个函数 [英] How to pass multiple function in raster::extract()

查看:122
本文介绍了如何在raster :: extract()中传递多个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用栅格CHM,并且必须从多边形shapefile中提取多个度量.现在我正在做这样的事情:

I'm working with a raster CHM and I've to extract several metrics from a polygon 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...)

我想知道是否有一种方法可以将所有摘要函数传递给extract()函数的fun =参数,并且是否可以并行执行.谢谢您的帮助.

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. Thanks for every help.

这是我在StackOverflow中的第一个问题,对于任何不当行为,我深表歉意.

N.B. this is my first question in StackOverflow, I apologize for any impropriety

推荐答案

正如@dww在上面的注释中建议的那样,这是一个函数,该函数计算大量摘要统计信息并将其作为向量返回.它被传递给 raster :: extract fun 参数.请注意, raster :: extract 中的文档说,该函数必须接受 na.rm 自变量.我无法更改用于提取数据框输出列的 extract 的默认行为,因此之后需要手动设置名称.

As @dww suggests above in the comments, here is a function which calculates a number of summary statistics and returns them as a vector. It is passed to the fun argument of raster::extract. Note that the documentation from raster::extract says that the function must accept a na.rm argument. 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.

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

输出

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

这篇关于如何在raster :: extract()中传递多个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆