I'm not showing you my real code because it's huge and ugly. But I recreated the problem using standard r packages:
# a list of a few r standard datasets
datasets <- list(PlantGrowth, cars, faithful)
# a function that plots a dataset and adds its name to the title
plotstuff <- function(dataset) {
plot_title <- substitute(paste("Plot of ", dataset, sep=" "))
plot(dataset, main = plot_title)
}
The name of the dataset (i.e. function argument) is successfully added to the plot title when I run the function with individual datasets like
plotstuff(PlantGrowth)
plotstuff(cars)
plotstuff(faithful)
Since I have many datasets I would like to do this with lapply like this:
lapply(datasets, plotstuff)
But in doing so I get weird titles: Plot of [[(X,i) instead of the name of the dataset. How do I make the name of the dataset appear in the plot titles using lapply?
Here's the only related topic I could find. (And it didn't really help...)
Use variable name as plot title with lapply
EDIT: Thanks! But I don't seem to understand the other example.
"Use lapply on the names of the list items instead:"
lapply(names(afn), function(x) plot(afn[[x]], main=x))
First, I add names to the list:
datasets <- list(PlantGrowth = PlantGrowth, cars = cars, faithful = faithful)
And then I tried:
plotstuff <- function(dataset) {
chart_title <- substitute(paste("Plot of ", dataset, sep=" "))
plot(datasets[[dataset]], main = chart_title)
}
lapply(names(datasets), plotstuff)
Did not work... I also don't want to reference the list datasets inside the function. What if I want to use a second list with another name later? Anybody know a solution for this example here?
lapplycould know them. Trynames(datasets). For comparison,L = list(a = 1, b = 2). - Frank