【问题标题】:Using xy=TRUE in R terra extract在 R terra 提取中使用 xy=TRUE
【发布时间】:2021-09-27 11:42:20
【问题描述】:

我正在尝试提取像素质心的坐标,我的点落在该像素内。这是一个可重现的例子

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

#Create random points in raster
points<-spatSample(r, 10, as.points=TRUE)
crds<-crds(points)
#Extract the coordinates of the random points
crds
            x        y
 [1,] 5.904167 49.97083
 [2,] 6.262500 50.12917
 [3,] 6.512500 49.63750
 [4,] 6.462500 50.03750
 [5,] 6.137500 49.90417
 [6,] 6.520833 49.96250
 [7,] 5.904167 49.52083
 [8,] 6.187500 49.68750
 [9,] 6.212500 49.68750
[10,] 5.962500 49.86250

#Extract pixel values and centroids of pixels
values<-extract(r, points, xy=TRUE)
values

ID  elevation          x         y
1 373.000000   6.462500  49.52083
2   5.904167  50.037500 367.00000
3  49.970833 368.000000   6.18750
4        NaN   6.137500  49.68750
5   6.262500  49.904167 392.00000
6  50.129167        NaN   6.21250
7        NaN   6.520833  49.68750
8   6.512500  49.962500 431.00000
9  49.637500 305.000000   5.96250
10        NaN   5.904167  49.86250

我希望提取的 x y 坐标仅略微偏离原始坐标,但这些值似乎都混在一起了。我的代码是否有错误,或者是否有其他获取这些值的方法?

【问题讨论】:

标签: r terra


【解决方案1】:

这适用于当前的 CRAN 版本 (1.3-4):

library(terra)
terra version 1.3.4
filename <- system.file("ex/elev.tif", package="terra")
r <- rast(filename)
 
set.seed(7222021)
points <- spatSample(r, 5, as.points=TRUE)
crds(points)
#            x        y
#[1,] 5.929167 49.67083
#[2,] 6.279167 49.94583
#[3,] 6.487500 49.84583
#[4,] 6.004167 49.49583
#[5,] 6.379167 49.62083
 
extract(r, points, xy=TRUE)
#  ID elevation        x        y
#1  1       323 5.929167 49.67083
#2  2       NaN 6.279167 49.94583
#3  3       NaN 6.487500 49.84583
#4  4       358 6.004167 49.49583
#5  5       283 6.379167 49.62083

要更新terra,您可以运行update.packages()。或者如果你只想更新terra,你应该先更新Rcpp

install.packages(c('Rcpp', 'terra'))

【讨论】:

    【解决方案2】:

    正如@Tung 所指出的,这目前是一个未解决的问题,似乎已在开发版本中得到解决。

    install.packages('terra', repos='https://rspatial.r-universe.dev')

    很遗憾,开发版在我的电脑上出现了一些问题。由于我的时间不多,因此使用我的可重现示例进行了一个不太漂亮的工作。

    filename <- system.file("ex/elev.tif", package="terra")
    r <- rast(filename)
    
    #Create random points in raster
    points<-spatSample(r, 10, as.points=TRUE)
    crds<-crds(points)
    
    cell<-cellFromXY(r, crds)
    xy<-xyFromCell(r, cell)
    xyvect<-vect(as.data.frame(xy), type="points",geom= c("x", "y"),crs(r))
    #points now contains my initial coordinates and xyvect contains 
    #the pixel centroid, which is this case are the same, but I tested it
    #with an actual dataset and it works.
    

    【讨论】:

    • 这些问题在不久前已经关闭,我认为 CRAN 版本可以正常工作。 “开发版本的问题”可能与 Rcpp 版本有关(您可能需要先更新 Rcpp)。
    猜你喜欢
    • 2021-08-29
    • 2021-12-17
    • 2021-05-30
    • 2021-09-16
    • 2021-11-26
    • 2022-12-28
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    相关资源
    最近更新 更多