gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:53:58 29 4
gpt4 key购买 nike

在土壤制图的框架中,我需要对不确定数量的栅格求和。我尝试使用 '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'

谢谢你的帮助,

弗朗索瓦

最佳答案

您可以使用 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)

至于为什么你原来的命令不起作用,那有点令人困惑。将函数名称作为字符提供似乎有效:
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)

但这在其他情况下不是必需的:
do.call(sum,list(1,2,3))
[1] 6

关于r - 使用 do.call 和 raster 包对不确定数量的栅格求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14260957/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com