首页 > 解决方案 > 如何在更改设置输出文件名的特定参数时将函数应用于列表

问题描述

我的问题是一般性的。您如何将以下函数(在本例中为假设的)应用于两个列表:R 中的 list_1 和 list_2。这些列表同样长并且它们是成对的。

function(argument1, argument2) # where argument one should be applied to list_1 and argument2 should be applied to list_2

一个可重现的例子可以是:

as.list(paste0("raster", seq(1:10))) -> list_1        # A made-up list of raster names. In real life, this should be a list of rasters.
as.list(paste0("file", seq(1:10), ".tif")) -> list_2  # A made-up list of file names.

library(gdalUtils)

gdal_translate(src_dataset =, dst_dataset = )
# where src_dataset argument should be applied to list_1 and dst_dataset argument should be applied to list_2

提前致谢。

标签: rfunctionapplylapplysapply

解决方案


mapply功能是我一直在寻找的。

# Define a function to be applied to the lists.
func2 <- function(x, y){
  gdal_translate(src_dataset = x, dst_dataset = y)
}
# Apply the function to the lists.
mapply(FUN = func2, list_1, list_2)

推荐阅读