【问题标题】:How to loop through rasters in R and give them names associated with the filename如何遍历 R 中的栅格并为其命名与文件名相关联
【发布时间】:2013-11-28 06:00:23
【问题描述】:

请帮助新手 :) 我正在尝试遍历文件中的栅格,只需将它们导入 R 并给它们取自文件名的名称。

我可以很好地得到一串路径名

# Establish path to raster files
hab = "C:\\Michelle\\Michelle\\R\\Variables"         
hab = list.files(path = hab, full.names = T, recursive = T)  # path to each file
hab = hab[substring(hab,nchar(hab)-2,nchar(hab))=="ovr"]     # keep the raster file path

然后我想出了如何遍历栅格,但我可以弄清楚如何用关联的文件名命名每个栅格。我可以用下面的第一行代码提取文件名....但是 .ovr 仍然附加。

#Extract File names for each raster
file = unlist(lapply(hab,function(x) strsplit(x,"/")[[1]][3]))   # vector of file names
#  process each raster in HAB
for(j in 1:length(hab) ){
    a = raster(hab[j])}

【问题讨论】:

    标签: r gis raster


    【解决方案1】:

    使用 assign 但请记住,您还可以通过将有效栅格矢量传递给函数来创建栅格堆栈或砖块。原始栅格名称保存在栅格对象中。但是,您的所有栅格都必须共享共同的分辨率、尺寸(行/列)、范围和原点坐标。如果你想预测一个空间模型,你可以使用这个输入并调用 predict。光栅包中有一个包装器,它将预测光栅堆栈/砖对象并保持内存安全。我对您的代码提出了一些建议。

    # if you set the working directory you do not need to return the full path in list.files.      
      setwd("C:/Michelle/Michelle/R/Variables")
    
    # Use pattern arg to return a wildcard for ovr
      hab = list.files(getwd(), pattern="ovr$", full.names=FALSE) 
    
    # Create raster stack and display associated names 
    r <- stack(hab)
      names(r)   
    
    # Here is how you return just the files names
      hab.names <- c( unlist( lapply(strsplit(hab,"[.]"), FUN=function(x) { x[1] })))   
    
    # For loop assigning files names to individual raster objects
      for(j in 1:length(hab) ) { assign(hab.names[j], raster(hab[j]) }
    

    【讨论】:

    • +1 表示stack,-1 表示“使用分配”。如果他们真的要遍历文件名并读取每个文件名(尽管老实说我不确定他们在做什么),我们不应该推荐assign。最好为栅格创建一个列表,然后只需使用 names&lt;-
    • 谢谢!我会试一试。互联网上到处都推荐堆栈,但栅格的大小和分辨率都不同。导入后,我将不得不在循环中添加裁剪和重新采样(在聚合一些之后)。
    • 如果您确信您的栅格对齐,您可以使用 quick=TRUE 参数并且堆栈函数不会检查分辨率和范围匹配。但是,除非您在 GIS 中设置捕捉参考以确保栅格的原点坐标匹配,否则这是非常危险的。
    猜你喜欢
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 2016-12-18
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多