RAS
RAS

Reputation: 121

Extract listed data frame names inside lapply

I am creating a list of plots from a list of data frames and am trying to add a title to each plot corresponding to the name of the data frame in the list. Outside of lapply if I call paste0(names(df.list)[x]) it returns the name of the data frame of interest.

When I try and add this within lapply

df.plots<-lapply(df.list, function(x) p<-ggplot(x,aes(x=Numbers,y=Signal)) + geom_point() + ggtitle(paste0(names(df.list)[x])) )

I get the following error:

Error in names(df.list)[x] : invalid subscript type 'list'

Is there another way I can extract the data frames names so I can add them to the plots?

Upvotes: 2

Views: 1495

Answers (2)

aosmith
aosmith

Reputation: 36086

You can use map2 from purrr to loop through the list and the names of the list simultaneously, creating a plot each time. In map2, the .x refers to the first list and .y refer to the second list, which you can use in your plotting code.

library(purrr)
map2(dlist, names(dlist), 
    ~ggplot(.x, aes(Numbers, Signal)) +
        geom_point() +
        ggtitle(.y))

Upvotes: 2

arvi1000
arvi1000

Reputation: 9582

This fails because the value of x is an element of the list df.list, which isn't something you can use to index a vector of names.

You could try lapply on an indexing vector instead, which is explained in the question aosmith linked (Access lapply index names inside FUN)

lapply(seq_along(df.list), function(i) {
    ggplot(df_list[[i]], aes(x=Numbers, y=Signal)) + 
      geom_point() + 
      ggtitle(names(df.list)[i])
}

(Also, not your directly related to your question, but calling paste0 doesn't do anything if you pass it just a single value, so you can drop that)

Upvotes: 1

Related Questions