I want to get values (pixels values), coordinates (x
and y
) and attribute (status
) in the neighborhood (for example in a buffer=6
meters) of random coordinates (pts
), using extract function in raster package. I try to organize the results in data.frame
without success.
library(raster)
#create some GeoTIFF rasters
r <- raster(ncol=10, nrow=10)
s <- stack(lapply(1:8, function(i) setValues(r, runif(ncell(r)))))
f1 <- file.path(tempdir(), "sl1.tif")
f2 <- file.path(tempdir(), "sl2.tif")
writeRaster(s[[1:4]], f1, overwrite=TRUE)
writeRaster(s[[5:8]], f2, overwrite=TRUE)
# 10 random points in the rasters
set.seed(5)
pts <- sampleRandom(s[[1]], 10, xy=TRUE)[,1:2]
status<-c(rep(c("A","B"),5))
pts<-as.data.frame(cbind(pts,status))
i<-c(1,2)
pts[ , i]<-apply(pts[ , i], 2,
function(x) as.numeric(as.character(x)))
#read all rasters
f <- c(f1, f2)
ras <- lapply(f, brick)
# extract raster values in 10 random coordinates and 6 meters around and organize the results
RES<-NULL
for(i in 1:length(ras)){
value <- raster::extract(ras[[i]],pts[,1:2], buffer=6)
RES<-rbind(RES,cbind(pts,coordinates(value),value)) #create a data frame of the results
}
RES
Error in data.frame(..., check.names = FALSE) :
arguments imply differing number of rows: 10, 4
I have a different number of rows of course!! I've like to create a final data frame output with random coordinates (xy in pts
), xy of neighborhood points (x2 and y2 pixels coordinates around of 6m buffer), status (repetition of pts
status, I consider that neighborhood has the same status of pts
father coordinate) and each layers values like:
x y x2 y2 status sl1.1 sl1.2 sl1.3 sl1.4 ...
1 -162 45 -165 48 A 0.47991386 0.04220410 0.79925156 0.04536868 0.47991386 ...
...