I want to add a new layer to a SpatialPixelsDataFrame
object using a RasterLayer
object. Here's an example:
# Packages
library(gstat)
library(sp)
# Example data set in SpatialPixelsDataFrame format
lat <- c(-23.49174, -23.49179, -23.49182, -23.49183, -23.49185, -23.49187)
long <- c(152.0718, 152.0718, 152.0717, 152.0717, 152.0717, 152.0717)
pH <- c(8.222411, 8.19931, 8.140428, 8.100752, 8.068141, 8.048852)
sample <- data.frame(lat, long, pH)
x.range <- range(sample$long)
y.range <- range(sample$lat)
x<-seq(x.range[1], x.range[2], length.out=20)
y<-seq(y.range[1], y.range[2], length.out=20)
grd<-expand.grid(x,y)
coordinates(sample) = ~long+lat
coordinates(grd) <- ~ Var1+Var2
gridded(grd) <- TRUE
proj4string(sample) <- CRS("+proj=longlat +datum=WGS84")
proj4string(grd) <- CRS("+proj=longlat +datum=WGS84")
dat.idw <- idw(formula=pH ~ 1, locations = sample, newdata = grd, idp = 2.0)
class(dat.idw)
# [1] "SpatialPixelsDataFrame"
# attr(,"package")
# [1] "sp"
# Now I'd like to add a new layer to the SpatialPixelsDataFrame using another SpatialPixelsDataFrame
lat <- c(-23.49174, -23.49179, -23.49182, -23.49183, -23.49185, -23.49187)
long <- c(152.0718, 152.0718, 152.0717, 152.0717, 152.0717, 152.0717)
temp <- c(20, 21, 22, 23, 24, 25)
sample <- data.frame(lat, long, temp)
x.range <- range(sample$long)
y.range <- range(sample$lat)
x<-seq(x.range[1], x.range[2], length.out=20)
y<-seq(y.range[1], y.range[2], length.out=20)
grd<-expand.grid(x,y)
coordinates(sample) = ~long+lat
coordinates(grd) <- ~ Var1+Var2
gridded(grd) <- TRUE
proj4string(sample) <- CRS("+proj=longlat +datum=WGS84")
proj4string(grd) <- CRS("+proj=longlat +datum=WGS84")
dat.idw.2 <- idw(formula=temp ~ 1, locations = sample, newdata = grd, idp = 1.5)
dat.idw.2 <- raster::raster(dat.idw.2)
class(dat.idw.2)
class(dat.idw.2)
# [1] "RasterLayer"
# attr(,"package")
# [1] "raster"
# Now I'd like to add dat.idw.2 to dat.idw
dat.idw$temp <- as(dat.idw.2, "SpatialGridDataFrame")$v
str(dat.idw)
# Formal class 'SpatialPixelsDataFrame' [package "sp"] with 7 slots
# ..@ data :'data.frame': 400 obs. of 2 variables:
# .. ..$ var1.pred: num [1:400] 8.05 8.05 8.06 8.06 8.07 ...
# .. ..$ var1.var : num [1:400] NA NA NA NA NA NA NA NA NA NA ...
# ..@ coords.nrs : int [1:2] 1 2
# ..@ grid :Formal class 'GridTopology' [package "sp"] with 3 slots
But the new layer (temp
) in @ data
is not added to the SpatialPixelsDataFrame
object. How can I add the new layer to the original SpatialPixelsDataFrame
object using a RasterLayer
?
Thanks!!