Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

r - Getting dataframe name inside a lapply function on a list (ggplot2)

I'm trying to get a dataframe name to use it as title in ggplot

#create dataframes
N1 <- N2 <- N3 <- N4 <- data.frame(matrix(1:12, 3, 4))

#list dataframes
mylist = list(N1, N2, N3, N4)

#rename dataframes in list
names(mylist) = c("N1", "N2", "N3", "N4")



#plot each ggplot using one data frame

myggplots =  lapply(mylist, function(x){
  require(ggplot2)
  a = ggplot(x, aes(x=X1, y = X2)) +
  geom_point() +
  ggtitle(paste0(x))
  a
})

If I access myggplots[[1]] , the title is not the name of the dataframe (N1 in this case). However, each plot object is named correctly after the dataframe that was used to create it

I tried many codes, without success. It is important to create a list of ggplots!

question from:https://stackoverflow.com/questions/65876600/getting-dataframe-name-inside-a-lapply-function-on-a-list-ggplot2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As it is a named list, we can use imap where the .y returns the name of the list element and .x the value of the element

library(ggplot2)
library(purrr)
out <- imap(mylist, ~ 
         ggplot(.x, aes(x = X1, y = X2)) + 
              geom_point() + 
              ggtitle(.y)
          )

With lapply, an option is to either loop over the sequence of list or the names and then extract the list element with [[

out <- lapply(names(mylist), function(nm)
            ggplot(mylist[[nm]], aes(x = X1, y = X2)) + 
               geom_point() + 
               ggtitle(nm)
      )

Or use Map

out <- Map(function(x, y) 
               ggplot(x, aes(x = X1, y = X2)) + 
                  geom_point() + 
                  ggtitle(y), 
                   mylist, names(mylist))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...