【发布时间】:2017-02-23 11:24:24
【问题描述】:
经常使用tidyverse,我经常面临将命名向量转换为data.frame/tibble 的挑战,其中列是向量的名称。
什么是首选/tidyversey这样做的方式?
编辑:这与:this 和 thisgithub-issue
所以我想要:
require(tidyverse)
vec <- c("a" = 1, "b" = 2)
变成这样:
# A tibble: 1 × 2
a b
<dbl> <dbl>
1 1 2
我可以通过例如:
vec %>% enframe %>% spread(name, value)
vec %>% t %>% as_tibble
用例示例:
require(tidyverse)
require(rvest)
txt <- c('<node a="1" b="2"></node>',
'<node a="1" c="3"></node>')
txt %>% map(read_xml) %>% map(xml_attrs) %>% map_df(~t(.) %>% as_tibble)
这给了
# A tibble: 2 × 3
a b c
<chr> <chr> <chr>
1 1 2 <NA>
2 1 <NA> 3
【问题讨论】:
-
你认为你正在做的事情到底有什么不足(如果有的话?)
-
我也问过自己同样的问题,因为
bind_rows不能代替map_df(~t(.) %>% as_tibble)工作。所以,到现在为止,我转置,转换为字符串保留字符(不是因子)的数据帧,然后将结果绑定在一起。但是,这个常见任务的快捷方式可能会很好。 -
@lukeA,我认为
bind_rows已经更新,现在可以按照您想要的方式工作
标签: r dplyr tidyr purrr tidyverse