光栅:如果坐标完全匹配,则替换值,如果不是 NA

问题描述

我想用 (r) 中的新值替换实际的栅格 (Class@data$layer) 值。但是,我的条件是,如果栅格 r 中的坐标与 Class 坐标 (SpatialPointsDataFrame) 完全匹配,则替换为新值 (layer),并在整个坐标替换为 NA。在我的例子中:

library(sp)  
library(dplyr)
library(raster)

# create raster
r <- matrix(rnorm(n=10000,mean=10),100,100)
r <- raster(r)
extent(r) <- c(544937,545916,7321332,7322524)
projection(r) <- "+proj=utm +zone=22 +ellps=wgs84 +units=m +no_defs"

# Selection of some coordinates that exists in the raster 
ras.coords <- as.data.frame(coordinates(r))
coords.sample <- ras.coords %>% sample_n(100)

# Create a new values
coords.sample$layer <- rpois(n=100,lambda=25)

# Convert  to SPDF
Class <- SpatialPointsDataFrame(coords = coords.sample[,1:2],data = as.data.frame(coords.sample[,3]),proj4string = crs(r))
names(Class) <-("layer")

#Rewrite raster values,but the values are populated if exist the coordinate correspondence if not replace by NA

r[cellFromXY(r,Class@coords)] <- Class@data$class

显然行不通,但它表达了我的目标。请问,对我的问题有什么帮助吗?

解决方法

如果我理解正确,你就可以了

x <- rasterize(Class,r,"layer")