Passing list element names as a variable to functions within lapply

放肆的年华 提交于 2021-02-08 03:45:29

问题


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)
}

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

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

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


回答1:


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")))



回答2:


In the OP's post, it looped through each element of the 'd.list', but called names(d.list) in each of the loop i.e. calling a vector (c("a", "b", "c")). We need to loop by the names of the 'd.list'. In that way, we can get the individual names as well as the list elements by subsetting.

 lapply(names(d.list), function(x) paste0(x, ".svg"))

If we are using the OP's function

 lapply(names(d.list), function(x) myfun(data= d.list[[x]],
                                      f.name = paste0(x, ".svg")))


来源:https://stackoverflow.com/questions/37094279/passing-list-element-names-as-a-variable-to-functions-within-lapply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!