【问题标题】:How to extract the values of a cell in a raster (in this case landcover type) with data points (coordinates) in a data frame如何使用数据框中的数据点(坐标)提取栅格(在本例中为土地覆盖类型)中的像元值
【发布时间】:2019-05-22 11:30:36
【问题描述】:

我有一个带有坐标的相机陷阱数据的数据框(称为“事件”),我想使用每个位置的栅格文件提取栖息地类型,并将栖息地类型添加到我的数据框中。如何使用栅格和数据框坐标提取它?之后如何将其添加到另一个主数据框中?

## Creating the raster file from a shapefile

myfile <- shapefile("dpky.lc5.shp")

myfile@data$VALUE<-as.numeric(myfile@data$VALUE) # VALUE gives the numeric code for habitat type.

sr <- "+init=EPSG:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"

r <- raster(myfile, res=100, crs=sr)

myraster<-rasterize(myfile,r,field="VALUE")

myras_spdf <- as(myraster, "SpatialPixelsDataFrame")

myras_df <- as.data.frame(myras_spdf)

## Data frame with coordinates

events <- read.csv("DPKY.Clean.csv",h=T,sep=";")

events.sp<-SpatialPoints(events[,c("Longitude","Latitude")],proj4string = CRS("+init=EPSG:4326"))

events.sp

我还没有找到任何代码来解决这个问题,但具体到我的问题。我确实使用了另一个 .gri 文件,但该代码不适用于此。

【问题讨论】:

  • 对我来说,如果没有一些示例数据,这是不可能说的..
  • 如何与您共享数据?
  • 您不应共享您的数据。相反,您应该像我在回答中所做的那样创建一些示例数据,正如您在本网站上的许多问题中所看到的那样。

标签: r dataframe coordinates extract raster


【解决方案1】:

您似乎有点和多边形,以及用点查询它们的值的内容。换句话说,从多边形中提取点的值。如果是这种情况,创建 RasterLayer(和/或 SpatialPixels)对象是没有意义的。

总是提供一些示例数据(p 有多边形,d 是带有坐标的 data.frame)

library(raster)
p <- shapefile(system.file("external/lux.shp", package="raster"))
set.seed(10)
d <- coordinates(spsample(p, 4, "regular"))
colnames(d) <- c("lon", "lat")
d <- data.frame(id=1:nrow(d), d)

解决方案

x <- extract(p, d[,c("lon", "lat")])

现在你可以做

cbind(d, x[,c(4,6)])
#  id      lon      lat     NAME_1           NAME_2
#1  1 5.889636 49.53576 Luxembourg Esch-sur-Alzette
#2  2 6.176340 49.53576 Luxembourg       Luxembourg
#3  3 5.889636 49.82246   Diekirch          Redange
#4  4 6.176340 49.82246   Diekirch         Diekirch

或者类似的东西

d$NAME_2 <- x$NAME_2
d
#  id      lon      lat           NAME_2
#1  1 5.889636 49.53576 Esch-sur-Alzette
#2  2 6.176340 49.53576       Luxembourg
#3  3 5.889636 49.82246          Redange
#4  4 6.176340 49.82246         Diekirch

【讨论】:

    猜你喜欢
    • 2018-09-17
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 2016-08-11
    • 2014-03-24
    • 2017-09-23
    • 2020-05-06
    相关资源
    最近更新 更多