简体   繁体   中英

How to add function argument as plot title with lapply?

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 (ie 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?

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

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