我在一个文件夹中有大约 4000 个栅格 (tif)。每个tis显示一个物种的分布。 tif 的文件名是物种名称。我想根据文件夹中的物种子集制作物种丰富度图。我有一个 csv 文件,其中包含我想要子集化的物种的文件名。我如何根据 csv 中列出的文件名读入 tifs 的子集?我还需要将 tifs 的子集导出到另一个文件夹。
我在网上做了很多搜索,但找不到任何有用的东西。
非常感谢您的帮助!
这是我的tif文件:
> head(f)
[1] "Abies_alba.tif" "Abies_cephalonica.tif" "Abies_nebrodensis.tif" "Ablepharus_budaki.tif"
[5] "Ablepharus_chernovi.tif" "Ablepharus_kitaibelii.tif"
这是我的 csv:
> head(csv)
BINOMIAL
1 Abies_alba
2 Abies_cephalonica
3 Abies_nebrodensis
您可以循环存储在 csv 中的值并使用
paste0
函数来制作路径:
library(raster)
library(ggplot2)
library(rasterVis)
origin_folder <- "C:/origin/"
destination_folder <- "C:/destination/"
csv_list <- data.frame(files = c("filename1", "filename2"))
# Loop over each filename
for (i in csv_list$files){
# Read the file from the origin folder
specie <- raster(paste0(origin_folder, i, ".tif"))
# Plot the heatmap
gplot(specie) + geom_tile(aes(fill = value))
# Save the file in the destination folder
writeRaster(specie, paste0(destination_folder, i, ".tif"))
}
使用下面的帮助,这是有效的代码:
origin_folder <- "C:/origin/"
destination_folder <- "C:/destination/"
csv <- read.csv("C:/CSV location.csv")
# Loop over each filename
for (i in csv$BINOMIAL){
# Read the file from the origin folder
specie <- raster(paste0(origin_folder, i, ".tif"))
# Save the file in the destination folder
writeRaster(specie, paste0(destination_folder, i, ".tif"))
}