2
votes

I am trying to plot several dataframes (one plot per dataframe) with a lapply function, but despite all the posts on this subject I could not find an answer as I keep getting an error: the output list of plots is empty.

My data is structured like this:

df1 <- mtcars %>% group_by(cyl) %>% tally()
colnames(df1) <- c('var', 'n')
df2 <- mtcars %>% group_by(gear) %>% tally()
colnames(df2) <- c('var', 'n')
dfList <- list(df1, df2)

dfList
[[1]]
# A tibble: 3 x 2
    var     n
  <dbl> <int>
1     4    11
2     6     7
3     8    14

[[2]]
# A tibble: 3 x 2
   var     n
  <dbl> <int>
1     3    15
2     4    12
3     5     5

I tried :

make_hist <- function(xvar){
     ggplot(dfList, aes_(x = ~var, y = as.name(xvar))) +
     geom_col() }

plots <- lapply(names(dfList), make_hist)

plots
list()

plots[1]
[[1]]
NULL
1

1 Answers

4
votes

Try this to plot your list of data frames. Your make_hist function was adjusted to handle a single data.frame. Then lapply can apply make_hist to each element of the list.

make_hist <- function(df){
  ggplot(df, aes(x = var, y = n)) +
    geom_col() }

plots <- lapply(dfList, make_hist)