如何使用R中的文件夹在循环中使用shapefile对象剪切栅格?

问题描述

伙计们。你好吗?

很高兴见到你。

我正在尝试从shapefile对象中剪切栅格(tif)

我的数据结构如下:

(种子文件夹)

种类1

种类2

种类3

我有不同种类的文件夹。在每个文件夹中,我都有不同的tiff模型和不同的shapefile。我需要的是一个脚本,该脚本使用同一文件夹中的shapefile文件剪切该种类文件夹内的所有栅格。然后转到下一个文件夹以执行相同的操作。我不需要剪切不在同一文件夹中的文件。我正在尝试下一个代码,但没有成功。我是R语言中的一个相对较新的用户,所以我将不胜感激。感谢大伙们。祝你有美好的一天。

setwd ("H:/Tesis_maestria/1_Eliposides/1_Cut_models")
library(purrr)
library(kuenm)
library(raster)
library(maptools)
library(rgeos)
library(rgdal)
rm(list=ls())

path_general <- "H:/Tesis_maestria/1_Eliposides/1_Cut_models"


dirs_especies_path <- list.dirs(full.names = T,recursive = F)

datum <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")

x=1
y=1
resultados_all <- seq_along(dirs_especies_path) %>% purrr::map_df(function(x){
   sp_mods <- list.files(dirs_especies_path[x],pattern = ".tif",full.names = TRUE)
   M <-list.files(dirs_especies_path[x],pattern=".shp",full.names = TRUE)
   r1 <- raster(sp_mods[y])
   cut_all <- seq_along(sp_mods) %>%  purrr::map_df(function(y){
   cor <-crop(r1,M)
   mas<-mask(cor,M)
   return(cut_all)
    })
     nwdf <- data.frame(cut_all,sp_name=dirs_especies_names[x])
                         setwd("H:/Tesis_maestria/1_Eliposides/1_Cut_models/cut")
    writeRaster(cut_all,filename=paste(M[[i]]),bylayer=T,suffix=names(stac),format="GTiff")
  return(nwdf)
})
print(resultados_all)

解决方法

经过一天的工作,我可以成功运行此代码。如下。我希望这可以帮助遇到同样问题的人。问候。

rm(list=ls())
library(rgdal)
library(raster)
library(maptools)
library(rgeos)
library(purrr)
rm(list=ls())

setwd("H:/Tesis_maestria/1_Eliposides/1_Cut_models1")
datum <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")

path_general <- "H:/Tesis_maestria/1_Eliposides/1_Cut_models1"

dirs_especies_path <- list.dirs(full.names = T,recursive = F)
                                
dirs_especies_names <- list.dirs(full.names = F,recursive = F)
                                 
#paste(path_general,dirs_especies_names,sep="")

##Presente##
for (i in 1:length(dirs_especies_path)){
    M <- list.files(dirs_especies_path[i],pattern = "csv.shp$",full.names = TRUE)
    mods <- list.files(dirs_especies_path[i],pattern = ".tif$",full.names = TRUE)
    stack <- raster::stack(mods)
    Ms <- shapefile(M)
    Ms@proj4string <- datum
    cor <- crop(stack,Ms)
    mas <- mask(cor,Ms)
    writeRaster(mas,filename=paste(M),bylayer=T,suffix=names(stack),format="GTiff")
    next}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...