r - 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!
解决方案
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]
推荐阅读
- javascript - 如何使用 gulp 在 js 文件中使用环境变量
- google-cloud-platform - 数据流需要 bigquery.datasets.get 授权视图中基础表的权限
- google-cloud-sdk - 谷歌云平台托管网站,但仅适用于 index.html
- python - 在 Altair 图表中隐藏构面标题?
- cassandra - Cassandra 中的每个表都应该有一个分区键吗?
- php - 如何在 symfony 4 和 Swiftmailer 中测试发送电子邮件
- python - 如何根据某些条件投射(长到宽)数据帧
- charts - Charts JS xAxes 不被数据共享
- php - strip_tags php 删除太多
- php - PHP如何foreach atts列出项目