RAS RAS - 7 months ago 60
R Question

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

if I call
it returns the name of the data frame of interest.

When I try and add this within

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?


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.

map2(dlist, names(dlist), 
    ~ggplot(.x, aes(Numbers, Signal)) +
        geom_point() +