简体   繁体   English

使用 terra 包而不是 raster 包的栅格运算引发错误

[英]Arthematic operations using rasters throwing errors using terra package not with raster package

I am trying to do some calculation on raster using following code我正在尝试使用以下代码对栅格进行一些计算

library(terra)

f <- system.file("ex/elev.tif", package="terra") 
r <- rast(f)

r_n <- (r - global(r, fun = "min", na.rm=TRUE))/
  (global(r, fun = "max", na.rm=TRUE) - global(r, fun = "min", na.rm=TRUE))

It throws the following error它抛出以下错误

Error in data.frame(value, row.names = rn, check.names = FALSE) : duplicate row.names: 374, 356, 348, 378,... data.frame 中的错误(值,row.names = rn,check.names = FALSE):重复的 row.names:374、356、348、378,...

But if I do it using raster R package, it runs fine like但是如果我使用raster R 包来做,它运行得很好

library(raster)

r_raster <- stack(r)
r_n_raster <- (r_raster - minValue(r_raster))/
  (maxValue(r_raster) - minValue(r_raster))

What should I do to make the code run with terra package?我应该怎么做才能使代码与terra包一起运行?

This happen because the ouput of global is a data.frame .You can simply convert the output of global to numeric with as.numeric or use the original summary function on the values of the raster:发生这种情况是因为global的输出是data.frame 。您可以使用as.numericglobal的输出简单地转换为数字,或者对栅格的values使用原始汇总函数:

rmin <- as.numeric(global(r, fun = "min", na.rm=TRUE))
rmax <- as.numeric(global(r, fun = "max", na.rm=TRUE))

r_n <- (r - rmin)/
  (rmax - rmin)

or或者

rmin <-  min(values(r), na.rm=T)
rmax <-  max(values(r), na.rm=T)

EDIT编辑

A microbenchmark of the two proposed method with the example data:带有示例数据的两种建议方法的微基准测试:

library(microbenchmark)
microbenchmark(global=as.numeric(global(r, fun = "min", na.rm=TRUE)),
               summary=min(values(r),na.rm=T))

output输出

Unit: microseconds
    expr    min      lq     mean median      uq     max neval cld
  global 2071.2 2157.40 2437.687 2223.6 2309.85 21725.9   100   b
 summary  729.2  756.35  844.381  794.4  824.15  5579.1   100  a 

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

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