r语言 - 从栅格匹配的csv和栅格文件名中提取值



我有一个文件夹与许多csv文件。每个文件都有几个列以及长列和长列。另一个文件夹有许多栅格在tif格式。csv文件是基于儒历日期命名的(例如251.csv),栅格也是如此(例如251.tif)。我希望能够将栅格值添加到具有匹配名称的csv并保存到r中的新csv。我想要实现的是:

raster<-raster("c:/temp/TIFF/2001/273.tif")
points<-read.csv("c:/temp/csv/2001/273.csv")
coordinates(points)=~long+lat
rasValue=extract(raster,points)
combinePointValue <- cbind(points,rasValue)
head(combinePointValue)
library(spdplyr)
combinePointValue <- combinePointValue %>% 
rename(chloro = 10)
write.table(combinePointValue,file="c:/temp/2001/chloro/273_chloro.csv",append=FALSE, 
sep=",",row.names=FALSE, col.names=TRUE)

考虑到许多csv和tif文件,我宁愿避免一遍又一遍地输入这个。有人能帮忙吗?提前感谢!的Ilaria

最好提供一个最小的可重复的示例,因为您的代码不能在没有特定数据的情况下运行。不过,如果我没理解错的话,你可以试试这样做。由于csv和tif文件具有相同的名称,因此可以对它们进行排序并遍历文件索引。您可以使用csv文件的原始路径来保存新文件,只需粘贴后缀"_chloro:

library(spdplyr)
csv <- sort(list.files("c:/temp/csv/2001/",full.names = T))
tif <- sort(list.files("c:/temp/TIFF/2001/",full.names = T))
lapply(1:length(csv),function(i){
raster<-raster(tif[i])
points<-read.csv(csv[i])
coordinates(points)=~long+lat
rasValue=extract(raster,points)
combinePointValue <- cbind(points,rasValue)
head(combinePointValue)
combinePointValue <- combinePointValue %>% 
rename(chloro = 10)
write.table(combinePointValue,file=paste0(tools::file_path_sans_ext(csv[i]),"_chloro.csv"),append=FALSE, 
sep=",",row.names=FALSE, col.names=TRUE)
}) 

SInce R空间"生态系统";在过去几年中经历了巨大的变化,并且像sp和raster这样的包将被弃用,您可以考虑基于terra包的解决方案。它会像这样:

# Not tested!    
library(terra)
csv_path = "c:/temp/csv/2001/"
tif_path = "c:/temp/TIFF/2001/"
tif_list = list.files(file.path(tif_path, pattern = "*.tif", full.names = FALSE)
result_list = lapply(1:length(tif_list), function(i) {
tif_file = file.path(tif_path, tif_list[i])
# Do not assume that the list of files are exactly equivalent.
# Instead create CSV file name from tif file
csv_name = gsub("tif", "csv", tif_file)
csv_file = file.path(csv_path, csv_name)
r = rast(tif_file)
csv_df = read.csv(csv_file)
# Assume csv long/lat are the same CRS as the tif files
pts = vect(csv_df, geom=c("long", "lat"), crs=st_crs(tif)) 
result = extract(r, pts, xy = TRUE)
new_csv = paste0(tools::file_path_sans_ext(csv_file),"_chloro.csv")
write.csv(result, file.path(csv_path, new_csv))
return(result)
})

相关内容

  • 没有找到相关文章

最新更新