将dataframe函数传递给gstat公式参数

时间:2018-10-05 20:52:02

标签: r lapply raster gstat

我正在尝试使用npm WARN checkPermissions Missing write access to /Users/username/Desktop/code/advocado/node_modules/jest-cli npm WARN checkPermissions Missing write access to /Users/username/Desktop/code/advocado/node_modules/node-pre-gyp npm WARN checkPermissions Missing write access to /Users/username/Desktop/code/advocado/node_modules/tar npm WARN checkPermissions Missing write access to /Users/username/Desktop/code/advocado/node_modules/regexpu-core npm WARN ajv-keywords@3.2.0 requires a peer of ajv@^6.0.0 but none is installed.' gstat()创建距离反距离加权栅格。我遇到了将列名传递给gstat函数的公式参数的问题。

硬编码列名可以正常工作:

raster::interpolate()

enter image description here

将其包装为一个函数,以便我可以遍历多个列名会引发错误:

gs <- gstat(formula=v1~1, locations = data)
r <- raster(shape, res=1000, crs = crs(data))
idw <- raster::interpolate(r, gs)
idwr <- mask(r, gs)
plot(idwr)

1 个答案:

答案 0 :(得分:1)

如果您使用as.formula(paste(col_name, '~1')),它可能会起作用 这是一个独立的示例:

library(raster)
library(gstat)
data(meuse)
r <- raster(system.file("external/test.grd", package="raster"))

gfun <- function(v) {
    mg <- gstat(formula = as.formula(paste(v, "~1")), locations= ~x+y, data=meuse, nmax=7, set=list(idp = .5))
    z <- interpolate(r, mg)
    mask(z, r)
}

vars <- c('cadmium', 'copper', 'lead', 'zinc')
x <- sapply(vars, gfun)
s <- stack(x)
s
#class       : RasterStack 
#dimensions  : 115, 80, 9200, 4  (nrow, ncol, ncell, nlayers)
#resolution  : 40, 40  (x, y)
#extent      : 178400, 181600, 329400, 334000  (xmin, xmax, ymin, ymax)
#coord. ref. : +init=epsg:28992 +towgs84=565.237,50.0087,465.658,-0.406857,0.350733,-1.87035,4.0812 +proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs 
#names       :     cadmium,      copper,        lead,        zinc 
#min values  :   0.3131223,  17.3430502,  42.3218862, 123.9369493 
#max values  :    11.91185,    97.28761,   470.70461,  1387.50615