提取并组织数据帧中的多波段栅格值

时间:2019-08-27 17:07:47

标签: r raster r-raster

我想用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"  

问题在于提取函数仅在一层中选择值,而我在所有层中都需要信息。拜托,有什么想法吗?

1 个答案:

答案 0 :(得分:1)

示例数据

library(raster)  
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)
# 5 random points in the rasters
set.seed(5)
pts <- sampleRandom(s[[1]], 5, xy=TRUE)[,1:2]

您在应该raster的地方使用了brick

f <- c(f1, f2)
ras <- lapply(f, brick)

提取

lapply(ras, function(r) extract(r, pts))

#[[1]]
#         sl1.1     sl1.2     sl1.3     sl1.4
#[1,] 0.9118225 0.3683489 0.9461193 0.5610859
#[2,] 0.7260444 0.2175285 0.1937144 0.1064423
#[3,] 0.2299451 0.4175407 0.1246593 0.6523710
#[4,] 0.9659587 0.5460171 0.4254940 0.2420936
#[5,] 0.6640411 0.3803043 0.3480674 0.9805962
#
#[[2]]
#         sl2.1       sl2.2     sl2.3     sl2.4
#[1,] 0.4129051 0.689537048 0.6562566 0.6587621
#[2,] 0.4662205 0.004840697 0.3207286 0.8606737
#[3,] 0.3988470 0.609101892 0.6140796 0.9177927
#[4,] 0.1542479 0.030588239 0.8145537 0.5056544
#[5,] 0.4548225 0.917027473 0.2570022 0.4182261