如何从 terra SpatRaster 构造经度、纬度、值数据框

How to constuct lon, lat, value dataframe from terra SpatRaster

我已经使用出色的 terra 包将单变量 .nc 文件作为 SpatRaster 对象读入 R,目的是根据像元质心拟合地统计模型。为此,我需要使用来自 SpatRaster 的数据构建一个数据框,其中的列对应于“经度、纬度、值”。这感觉像是一项可能有标准解决方案的任务,但我不熟悉 R 的空间统计生态系统。

任何 advice/suggestions 将不胜感激。

library(terra)
#> Warning: package 'terra' was built under R version 4.0.5
#> terra version 1.3.22

r <- rast(ncol=10, nrow=10)
values(r) <- runif(ncell(r))
plot(r)

p <- terra::as.points(r)
df <- data.frame(values(p), geom(p))
head(df)
#>       lyr.1 geom part    x  y hole
#> 1 0.9557333    1    1 -162 81    0
#> 2 0.2974196    2    1 -126 81    0
#> 3 0.9703617    3    1  -90 81    0
#> 4 0.3046196    4    1  -54 81    0
#> 5 0.7334711    5    1  -18 81    0
#> 6 0.8880635    6    1   18 81    0

使用函数terra::as.data.frame()更直接。参见 https://rspatial.github.io/terra/reference/as.data.frame.html

library(terra)
#> terra version 1.3.4

# make test raster with terra::rast()
a <- terra::rast(ncols = 10, nrows = 10, 
                 xmin = -84, xmax = -83, 
                 ymin = 42, ymax = 43)

# give it some values
values(a) <- 1:ncell(a)
plot(a)

a_df <- terra::as.data.frame(a, xy = TRUE, na.rm = FALSE) 
# take special note of default values

head(a_df)
#>        x     y lyr.1
#> 1 -83.95 42.95     1
#> 2 -83.85 42.95     2
#> 3 -83.75 42.95     3
#> 4 -83.65 42.95     4
#> 5 -83.55 42.95     5
#> 6 -83.45 42.95     6

packageVersion("terra")
#> [1] '1.3.4'
sessionInfo()
#> R version 4.1.0 (2021-05-18)
#> Platform: x86_64-apple-darwin17.0 (64-bit)
#> Running under: macOS Big Sur 10.16
#> 
#> Matrix products: default
#> BLAS:   /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRblas.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib
#> 
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#> [1] terra_1.3-4
#> 
#> loaded via a namespace (and not attached):
#>  [1] Rcpp_1.0.7        codetools_0.2-18  lattice_0.20-44   digest_0.6.27    
#>  [5] withr_2.4.2       grid_4.1.0        magrittr_2.0.1    reprex_2.0.0     
#>  [9] evaluate_0.14     highr_0.9         rlang_0.4.11      stringi_1.7.3    
#> [13] cli_3.0.1         fs_1.5.0          sp_1.4-5          raster_3.4-13    
#> [17] rmarkdown_2.9     tools_4.1.0       stringr_1.4.0     glue_1.4.2       
#> [21] xfun_0.24         yaml_2.2.1        compiler_4.1.0    htmltools_0.5.1.1
#> [25] knitr_1.33

reprex package (v2.0.0)

于 2021-10-21 创建