我想將資料框中的點繪制到我擁有的柵格圖層中。對于每個點,我希望單元格的值為 1(初始柵格層上的所有其他單元格的值都為零)。
我的資料框(資料)看起來像這樣(僅前三行)
Year<-c(2020, 2019, 2018)
Lat<-c(48.3,48.79,48.4)
Long<-c(-123.62, -123.36, -123.29)
我設法用以下代碼繪制了這些點
points = st_as_sf(data, coords = c("Long", "Lat"), crs = 4326)
plot(st_geometry(points), pch=16, col="navy")
并得到了這張圖: Graph points plotted
我現在想將這些點繪制到該區域的柵格圖層中。我的柵格圖層的引數如下:
class : RasterLayer
dimensions : 44, 41, 1804 (nrow, ncol, ncell)
resolution : 0.2916667, 0.2916667 (x, y)
extent : -133.2625, -121.3042, 41.3875, 54.22083 (xmin, xmax, ymin, ymax)
crs : NA
names : Blank_Map
此柵格的每個單元格的值為 0,這正是我所需要的。現在,我想將資料幀中的點添加到該柵格層,對這些資料點所在的每個單元格使用值 1。我還想將整個事物保存為一個新的柵格圖層(然后將具有 0 和 1 值)。
有人可以幫助我實作這一目標嗎?我已經嘗試了幾天,但似乎沒有任何幫助,任何幫助表示贊賞!
uj5u.com熱心網友回復:
1. 請在下面找到提供使用raster和sf庫的可能解決方案的 reprex 。
library(raster)
library(sf)
# Create from scratch the raster with 0 values
raster0 <- raster(nrows = 44, ncols = 41,
xmn = -133.2625, xmx = -121.3042,
ymn = 41.3875, ymx = 54.22083,
vals=0)
# Convert points 'sf' object into 'sp' object
points_sp <- as(points, "Spatial")
# Extract the cells of raster0 matching the points geometry of the 'sp' object
cells_ID <- extract(raster0, points_sp, cellnumbers=TRUE)[,"cells"]
# Copy raster0 (as you want the final result in another raster)
raster01 <- raster0
# Replace 0 values to 1 for cells matching points geometry in the 'raster01'
raster01[cells_ID] <- 1
# Visualization of the final result
plot(raster01)

由reprex 包(v2.0.1)于 2021 年 12 月 7 日創建
2. 請在下面找到一個 reprex 提供另一種使用terra和sf庫的解決方案
library(terra)
library(sf)
# Create from scratch the 'SpatRaster' with 0 values
raster0 <- rast(nrows=44, ncols=41,
nlyrs=1,
xmin=-133.2625, xmax=-121.3042,
ymin=41.3875, ymax=54.22083,
vals = 0)
# Convert points 'sf' object into 'SpatVector' object
points <- vect(points)
# Extract the cells of raster0 matching the points geometry of the 'sp' object
cells_ID <- terra::extract(raster0, points, cells = TRUE)
# Copy raster0 (as you want the final result in another raster)
raster01 <- raster0
# Replace 0 values to 1 for cells matching points geometry in the 'raster01'
raster01[cells_ID[,"cell"]] <- 1
# Visualization of the final result
plot(raster01)

由reprex 包(v2.0.1)于 2021 年 12 月 7 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376305.html
