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