I've like to create a data frame with the values of multi-band raster (rasters sl1 and sl2 with 4 layers in each raster) in 5 random coordinates (ptS), but unfortunately, my output was 10 values and I expected 80 values in my final data frame.
In my code I make:
library(raster)
# Example data
r <- raster(ncol=10, nrow=10)
# 10 layers
s <- stack(lapply(1:8, function(i) setValues(r, runif(ncell(r)))))
#Create two GeoTIFF with 4 layers
sl1<-s[[1:4]]
writeRaster(sl1,filename=paste("sl1",sep=""),
format="GTiff",datatype="FLT4S",overwrite=TRUE)
sl2<-s[[5:8]]
writeRaster(sl2,filename=paste("sl2",sep=""),
format="GTiff",datatype="FLT4S",overwrite=TRUE)
#Read rasters in batch
f <- list.files(getwd(), pattern = ".tif")
ras <- lapply(f,raster)
# Simulation of 5 random points in the rasters
pt<-rbind(coordinates(ras[[1]]),coordinates(ras[[1]]))
randomRows = function(df,n){
return(df[sample(nrow(df),n),])
}
ptS<-randomRows(pt,5)
# Extract raster values in random coordinates and create a data frame of the results
RES<-NULL
for(i in 1:length(ras)){
value <- raster::extract(ras[[i]],ptS)
dummy<-1:length(DF)
RES<-rbind(RES,cbind(ptS,paste(substr(f[1],1,3)),value,dummy))
}
str(RES)
chr [1:10, 1:5] "-126" "126" "-126" "-90" "-126" "-126" "126" "-126" "-90" ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:5] "x" "y" "" "value" ...
head(RES)
x y value dummy
[1,] "-126" "63" "sl1" "0.52498596906662" "1"
[2,] "126" "63" "sl1" "0.702012658119202" "2"
[3,] "-126" "63" "sl1" "0.52498596906662" "3"
[4,] "-90" "-63" "sl1" "0.522934257984161" "4"
[5,] "-126" "-81" "sl1" "0.115565001964569" "5"
[6,] "-126" "63" "sl1" "0.537986099720001" "1"
The problem is that the extract function select values in just one layer and I need the information in all layers. Please, any ideas?
ras <- lapply(f, stack)
because your current callras <- lapply(f, raster)
is only reading the first layer. That should solve the problem. – qdread