【问题标题】:how to efficiently import multiple raster (.tif) files into R如何有效地将多个光栅(.tif)文件导入 R
【发布时间】:2018-10-10 18:50:47
【问题描述】:

我是 R 新手,尤其是在空间数据方面。我正在尝试找到一种方法将多个(~600)单波段栅格(.tif)文件有效地导入 R,所有文件都存储在同一个文件夹中。不确定这是否重要,但请注意,在我的 Mac 和 Windows Parallel VM 上的文件夹中查看时,每个 .tif = .TIF 有以下五 (5) 种文件格式; .tfw; .TIF.aux.xml; .TIF.ovr; .TIF.xml。无论如何,以下代码(以及我尝试过的其他类似变体)似乎不起作用:

library(sp)
library(rgdal)
library(raster)

#path to where all .tif files are located
setwd("/path/to/workingdirectory")

#my attempt to create a list of my .tif files for lapply
temp = list.files(pattern="*.tif")
temp #returns 'character(0)'

#trying to use the raster function to read all .tif files
myfiles = lapply(temp, raster)
myfiles #returns 'list()'

有没有办法使用某种形式的循环来有效地导入所有光栅文件?

【问题讨论】:

  • 你是什么意思 tif = .TIF? R 区分大小写,因此与扩展名对齐。试试pattern="*.TIF"

标签: r lapply spatial raster tiff


【解决方案1】:

如果栅格的范围相同,您可以简单地将它们加载到堆栈中

#first import all files in a single folder as a list 
rastlist <- list.files(path = "/path/to/wd", pattern='.TIF$', all.files=TRUE, full.names=FALSE)

library(raster)
allrasters <- stack(rastlist)

【讨论】:

    【解决方案2】:

    我找到了答案,并将发布完整代码以帮助遇到此问题的其他初学者 R 用户。要调用列表元素,请使用方括号 [[]],如下所示:

    #first import all files in a single folder as a list 
    rastlist <- list.files(path = "/path/to/wd", pattern='.TIF$', 
    all.files=TRUE, full.names=FALSE)
    
    #import all raster files in folder using lapply
    allrasters <- lapply(rastlist, raster)
    
    #to check the index numbers of all imported raster list elements
    allrasters
    
    #call single raster element
    allrasters[[1]]
    
    #to run a function on an individual raster e.g., plot 
    plot(allrasters[[1]])
    

    嘘。感谢 Parfait 的帮助。

    【讨论】:

      【解决方案3】:

      好的,好的,我认为以下代码有效:

      rastlist <- list.files(path = "/path/to/wd", pattern='.TIF$', all.files=TRUE, 
      full.names=FALSE)
      lapply(rastlist, raster)
      

      但是现在如何访问单个栅格文件以进行进一步分析?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-04
        • 1970-01-01
        • 2022-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-23
        • 1970-01-01
        相关资源
        最近更新 更多