【发布时间】:2019-12-31 21:53:05
【问题描述】:
我想创建一个数据框,其中包含 5 个随机坐标 (ptS) 中的多波段栅格(栅格 sl1 和 sl2,每个栅格中有 4 个图层)的值,但不幸的是,我的输出是 10 个值,我在我的最终数据框中预期有 80 个值。
在我的代码中:
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"
问题是提取函数仅在一层中选择值,而我需要所有层中的信息。请问有什么想法吗?
【问题讨论】:
-
当您重新读取 GeoTIFF 时,您应该调用
ras <- lapply(f, stack),因为您当前的调用ras <- lapply(f, raster)仅读取第一层。这应该可以解决问题。 -
非常感谢!!如此简单且有效!