使用do.call和raster包对未确定数量的栅格求和

fst*_*ens 7 r raster

在土壤测绘的框架中,我需要总结不确定数量的栅格.我尝试使用'raster'包和'do.call'函数来完成它.但是,如果'sum'函数可以总计多个栅格,则使用do.call执行相同的操作会导致错误.我究竟做错了什么 ?

library(raster)

r1 <- raster(ncol=10, nrow=10)   # dataset for test
values(r1) <- runif(ncell(r1))
r2 <- raster(ncol=10, nrow=10)
values(r2) <- runif(ncell(r2))
r3 <- raster(ncol=10, nrow=10)
values(r3) <- runif(ncell(r3))

sum(r1,r2,r3)    # works nice

do.call(sum,list(r1,r2,r3))

##Erreur dans as.character(sys.call()[[1L]]) : 
##cannot coerce type 'builtin' to vector of type 'character'
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助,

弗朗索瓦

Jam*_*mes 8

您可以使用Reduce+计算列表中的总和:

Reduce("+",list(r1,r2,r3))
class       : RasterLayer 
dimensions  : 10, 10, 100  (nrow, ncol, ncell)
resolution  : 36, 18  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 
data source : in memory
names       : layer 
values      : 0.4278222, 2.476625  (min, max)
Run Code Online (Sandbox Code Playgroud)

至于为什么你的原始命令不起作用,这有点令人困惑.将函数名称作为字符提供似乎有效:

do.call("sum",list(r1,r2,r3))
class       : RasterLayer 
dimensions  : 10, 10, 100  (nrow, ncol, ncell)
resolution  : 36, 18  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 
data source : in memory
names       : layer 
values      : 0.4278222, 2.476625  (min, max)
Run Code Online (Sandbox Code Playgroud)

但在其他情况下不需要这样做:

do.call(sum,list(1,2,3))
[1] 6
Run Code Online (Sandbox Code Playgroud)