简体   繁体   中英

Passing list element names as a variable to functions within 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)
}

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 (egasvg, 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 ?

如果您需要同时遍历两个向量(数据和文件名),请使用mapply (或Map

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

In the OP's post, it looped through each element of the 'd.list', but called names(d.list) in each of the loop ie 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")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM