gpt4 book ai didi

r - 如何使用 lapply 在 R 中批处理 geoTIFF

转载 作者:行者123 更新时间:2023-12-02 08:10:29 33 4
gpt4 key购买 nike

我有一些大的 geoTIFF,现在我想将它们转换为 ASCII 文件,经过一些搜索后,我编写了这些代码:

library(raster)

f <- list.files("inputFolder", pattern = "*.tif", full.names = TRUE)
r <- lapply(f, raster)
a <- lapply(r, writeRaster, filename = "output", format = "ascii")

令我困惑的是,如何根据其原始名称分别命名输出文件?

我试过:

a <- lapply(r, writeRaster, filename = "outputFolder" + f, format = "ascii")

但我收到错误:

non-numeric argument to binary operator

然后我尝试了:

a <- lapply(r, writeRaster, filename = paste0(f, ".asc"), format = "ascii")

但是我收到了:

Error in file(filename, "w") : invalid 'description' argument In addition: Warning messages: 1: In if (filename == "") { : the condition has length > 1 and only the first element will be used 2: In if (!file.exists(dirname(filename))) { : the condition has length > 1 and only the first element will be used 3: In if (toupper(x@file@name) == toupper(filename)) { : the condition has length > 1 and only the first element will be used 4: In if (trim(filename) == "") { : the condition has length > 1 and only the first element will be used 5: In if (!file.exists(dirname(filename))) { : the condition has length > 1 and only the first element will be used 6: In if (filename == "") { : the condition has length > 1 and only the first element will be used 7: In if (!overwrite & file.exists(filename)) { : the condition has length > 1 and only the first element will be used

最佳答案

我想你基本上已经差不多了,有两个更正:

首先,您要调用 writeRaster因为它的副作用(即它能够将文件写入您的文件系统)所以您不需要分配 lapply() 的输出循环到一个对象。所以,删除 a <-我们有:

lapply(r, writeRaster, filename = paste0(f, ".asc"), format = "ascii")

接下来,filename参数不会遍历 f这样。您有两个选择,其中最简单的可能是传递 @file@name r 的插槽到 filename使用匿名函数的参数:

lapply(r, function(x) {
writeRaster(x, filename = x@file@name, format = "ascii", overwrite = TRUE)
})

您的另一个选择是遍历 rf像在 python 中一样与 for r, f in... 并行, 这可以用 purrr 来完成:

library("purrr")
walk2(r, f, function(x, y) {
writeRaster(x = x, filename = y, format = "ascii")
})

这里我们使用 walk2()而不是 map2()因为我们需要调用函数来产生副作用。这循环遍历 rf放在一起,这样您就可以传递一个作为要写入的对象,一个作为文件名。


编辑:这是我用来重现问题的代码

library("raster")

tmp_dir = tempdir()
tmp = tempfile(tmpdir = tmp_dir, fileext = ".zip")

download.file(
"http://biogeo.ucdavis.edu/data/climate/cmip5/10m/cc26bi50.zip",
destfile = tmp
)
unzip(tmp, exdir = tmp_dir)

f = list.files(tmp_dir, pattern = ".tif$", full.names = TRUE)
r = lapply(f, raster)

# Solution one
lapply(r, function(x) {
writeRaster(x, filename = x@file@name, format = "ascii", overwrite = TRUE)
})

# solution two
library("purrr")
walk2(r, f, function(x, y) {
writeRaster(x = x, filename = y, format = "ascii")
})

关于r - 如何使用 lapply 在 R 中批处理 geoTIFF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47591678/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com