0
votes

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?

1
Your list does not have names, so there's no way the lapply could know them. Try names(datasets). For comparison, L = list(a = 1, b = 2). - Frank
Name the list, then use the linked duplicate as guidance. - Rich Scriven
Thanks! Done that. I'm still stuck though (see edit)... - Mire Mike

1 Answers

0
votes

Like the other question, lapply won't do what you want here. When it applies the function it applies it to the element of the list, not the items that were used to create the list.

How about:

datasets <- list(PlantGrowth = PlantGrowth, cars = cars, faithful = faithful)

plotstuff <- function(dataset, name) {
  plot_title <- paste("Plot of ", name, sep=" ")
  dev.new()
  plot(dataset, main = plot_title)
}

mapply(plotstuff, dataset = datasets, name = names(datasets))