how to get the variable list from each data frame in a list

Viewed 19

I have a list of df, and I would like to rename the df as df1, df2, df3. and then create a summary like below to capture the variables in each df. What should I do?

enter image description here

I tried to use map to setNames for the data frames in lst, but I must do it in the wrong way. my current codes set variable names to df1, df2, def3.

lst<- map( lst ~
  setNames(.x, str_c("df", seq_along(lst))))

sample data:

lst<-list(structure(list(ID = c("Tom", "Jerry", "Mary"), Score = c(85, 
85, 96), Test = c("Y", "N", "Y")), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame")), structure(list(ID = c("Tom", "Jerry", 
"Mary", "Jerry"), Score = c(75, 65, 88, 98), try = c("Y", NA, 
"N", NA)), row.names = c(NA, -4L), class = c("tbl_df", "tbl", 
"data.frame")), structure(list(ID = c("Tom", "Jerry", "Tom"), 
    Score = c(97, 65, 96), weight = c("A", NA, "C")), row.names = c(NA, 
-3L), class = c("tbl_df", "tbl", "data.frame")))
1 Answers

We get the column names with names/colnames by looping, paste to a single string with toString, convert to a data.frame column and bind the elements (_dfr).

library(purrr)
library(dplyr)
library(stringr)
setNames(lst, str_c("df", seq_along(lst))) %>%
    map_dfr(~ tibble(Var = toString(names(.x))), .id = 'Data')

-output

# A tibble: 3 × 2
  Data  Var              
  <chr> <chr>            
1 df1   ID, Score, Test  
2 df2   ID, Score, try   
3 df3   ID, Score, weight
Related