首页 > 解决方案 > How to extract column headers (variables names) of data frames and store them as variable in a different data frame?

问题描述

I have three data frames with a different number of columns and observations. I would like to create a new data frame which lists all of the different variables from each data frame and specify the file name.

I have three data frames:

library(tibble)
library(magrittr)

a<-tibble(
 z=c(1,2,3),
 y=c(4,5,6),

)

b<-tibble(
  n=c(1,2),
  q=c(4,5),
  r=c(3,6),
)

c<-tibble(
  l=c(1,2),
  e=c(4,5),
  d=c(3,6),
)

I can easily extract the column names for one data frame and also specify which file it came from.

df<-as.data.frame(names(a))%>%
  dplyr::mutate(sheet=deparse(substitute(a)))

How do I iterate this over multiple data frames and save out a data frame as shown below:

df<-tibble::tibble(
  name=c("z", "y", "n", "q", "r", "l", "e", "d"),
  sheet=c("a", "a","b", "b", "b", "c", "c", "c")
)

head(df)
#> # A tibble: 6 x 2
#>  name  sheet
#>   z     a    
#>   y     a    
#>   n     b    
#>   q     b    
#>   r     b    
#>   l     c

I would like to do this using purrr but I am still in the learning stage. Any help would be appreciated!

标签: rdataframepurrr

解决方案


An option is to placee it in list, extract the names, enframe to a two column data.frame, and unnest the 'value' column

library(tidyverse)
lst(a, b, c) %>% 
    map(names) %>%
    enframe %>% 
    unnest

If we need a class column as well

lst(a, b, c) %>%
       map_dfr(~ tibble(name = names(.x), Class = map_chr(.x, class)), 
          .id = 'grp') 

In base R

stack(lapply(mget(c('a', 'b', 'c')), names))[2:1]

推荐阅读