将列表元素名称作为变量传递给 lapply 中的函数

问题描述:

我有一个命名的数据列表和一个我想应用于数据的自定义函数:

I have a named list of data and a custom function I want to apply to the data:

#Some example data
d.list <- list(a = c(1,2,3), b = c(4,5,6), c = c(7,8,9))

#A simple function to process some data, write an output graph, and return an output
myfun <- function(data, f.name) {
  y <- list()
  y[1] <- data[1] + data[2] + data[3]
  y[2] <- data[3] - data[1]/ data[2]
  y[3] <- data[2] * data[3] - data[1]
  svg(filename = f.name, width = 7, height = 5, pointsize = 12)
  plot.new()
  plot(data, y)
  dev.off()
  return(y)
}

我现在想使用 sapply 对我的列表进行迭代,并为每次迭代获取一个保存的图像文件,文件名设置为列表元素名称(egasvg、b.svg、c.svg 在上面的例子中),以及包含计算结果的数据框.当我运行这个:

I now want to iterate this over my list using sapply and get a saved image file for each iteration, with the file name set as the list element name (e.g. a.svg, b.svg, c.svg in the example above), along with the data frame containing results of the calculations. When I run this:

#Iterate over the example data using sapply
res <- t(sapply(d.list, function(x) myfun(data=x, 
                  f.name=paste(names(d.list), ".svg", sep = ""))))

我得到了预期的数据框:

I get the expected data frame:

  [,1]  [,2] [,3]
a    6 2.500    5
b   15 5.200   26
c   24 8.125   65

但我最终在目标目录中只有一个文件:a.svg"

but I only end up with one file in the target directory: "a.svg"

如何将列表元素名称作为参数正确传递给我在 sapply 中调用的函数?

How can I pass the list element names through correctly as a parameter to the function I'm calling in sapply?

如果您需要同时迭代两个向量(数据和文件名),请使用 mapply(或地图)

If you need to iterate over two vectors at the same time (both your data and the file names), use mapply (or Map)

res <- t(mapply(myfun, d.list, paste0(names(d.list), ".svg")))