I'd like to replace the actual raster (r
) values with new values in (Class@data$layer
). But, my condition is if the coordinates in raster r
exactly match with Class
coordinates (SpatialPointsDataFrame
), then replace with the new values (layer
), and all over the coordinates replace with NA. In my example:
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
Obviously doesn't work, but it expresses my goal. Please, any help with my problem?
If I understand you correctly, you can just do
x <- rasterize(Class, r, "layer")