光栅:如果坐标完全匹配,则替换值,如果不匹配,则替换 NA
Raster: if the coordinates exactly match replace the values, if not NA
我想用 (Class@data$layer
) 中的新值替换实际栅格 (r
) 值。但是,我的条件是,如果光栅 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")
我想用 (Class@data$layer
) 中的新值替换实际栅格 (r
) 值。但是,我的条件是,如果光栅 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")