[英]Resample and matching raster stack using loop in R
我的目标是将生物多样性数据与土地覆盖信息(栅格和矢量)结合起来。 但是,我需要将每个栅格(预测变量)的分辨率、范围、CRS 和维度与我的生物多样性数据(答案变量)相匹配。 我已经成功地单独完成了,但是有六个光栅。 虽然,当我尝试对栅格堆栈进行循环时。 我有一些错误。
library(terra)
library(raster)
#Create a raster stack with land cover predictors:
CDI_stack<-raster::stack(list.files(path = dir_Proj1, pattern='.tif', full.names=T))
#Convert to cylindrical equal area projection
equalareaproj<-"+proj=cea +lon_0=0 +lat_ts=30 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
crs(CDI_stack, warn=FALSE)<-equalareaproj
#Raster with standard dimension, resolution, extention and CRS
standard<-terra::subset(study_area, 2)
#Loop for the raster stack
for(i in 1:length(CDI_stack@layers)){
#Creating a single raster with each layer to maintain values
CDI_layer<-terra::rast(terra::subset(CDI_stack, i))
#Matching a raster extention individually
CDI_layer<-ext(standard)
#Cropping it with standard raster to reduce matching error
raster::crop(CDI_layer[i],standard)
#Resample resolution
terra::resample(CDI_layer[i], standard, method= "near", threads= T)
#Write the raster:
return(writeRaster(Resampled_layer,
filename=paste0("~/Land use/Chronic_Anthropogenic_Disturbance_Surface/", CDI_layer[i]),
format="GTiff", overwrite=TRUE))
}
我发现了这些错误:
Error in h(simpleError(msg, call)) :
error evaluating argument 'x' in method selection for function 'crop': 'this S4 class is not subsettable
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘crop’ for signature ‘"numeric"’
我想知道使用光栅堆栈是否有任何并发症,或者我是否错误地执行了任何代码步骤。 我希望在代码或 class object 的使用中找到更正。
拜托了,希望大家多多支持。 谢谢你。 G。
当您逐行运行代码时,应该很容易找出问题所在; 包括 for 循环内部(将i
设置为 1 或发生错误时的任何值)。
你会看到这失败了:
CDI_layer <- ext(standard)
raster::crop(CDI_layer[i],standard)
因为CDI_layer[i]
是一个单一的数字。
还有其他一些尴尬的事情。 特别是,只使用“terra”,不要同时使用“raster”,以免混淆。
感谢您的建议,Hijimanns 先生。 我发现错误太多了。 我更喜欢使用栅格堆栈中的列表而不是堆栈,它在循环中工作得更好。 此外,我使用矢量来裁剪栅格,它保留了栅格值(避免返回 NA)。
#Create a list from the stack with land cover predictors:
CDI_list<-terra::as.list(CDI_stack)
rm(study_area,CDI_stack)
#Create a list to store the results
results <- list()
#Loop for each SpatRaster from the list
for(i in 1:length(CDI_list)) {
r<-rast(CDI_list[[i]]) # create a raster for each layer
ext(r) <-ext(standard) # redefine extension for each layer
#Crop rasters using the vector to avoid 'NA' values
rc <- terra::crop(r, standard_vec)
#Resample rasters following standard parameters
rc <- terra::resample(rc, standard, method= "bilinear", threads= T)
#Rewrite the list layers with the result
results[[i]] <- rc
}
#Check the values
results[[4]]
#Rasterize the list to save it as a data frame
resampled<-rast(results)
df<-as.data.frame(resampled)
summary(df)
#Save the data frame in the project directory
data.table::fwrite(df, "~/Land use/DATASETS/resampled.csv")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.