问题
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