Ren*_*rop 14 r dplyr tidyr purrr tidyverse
使用tidyverse了很多我经常面临的挑战是将命名向量转换为data.frame/ tibble,其中列是向量的名称.
这样做的首选/ tidyverse方式是什么?
编辑:这与:这和这个 github问题有关
所以我想:
require(tidyverse)
vec <- c("a" = 1, "b" = 2)
Run Code Online (Sandbox Code Playgroud)
成为这个:
# A tibble: 1 × 2
a b
<dbl> <dbl>
1 1 2
Run Code Online (Sandbox Code Playgroud)
我可以通过例如:
vec %>% enframe %>% spread(name, value)
vec %>% t %>% as_tibble
Run Code Online (Sandbox Code Playgroud)
用例:
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)
Run Code Online (Sandbox Code Playgroud)
这使
# A tibble: 2 × 3
a b c
<chr> <chr> <chr>
1 1 2 <NA>
2 1 <NA> 3
Run Code Online (Sandbox Code Playgroud)
mar*_*dly 19
现在使用bind_rows(介绍dplyr 0.7.0)直接支持:
library(tidyverse))
vec <- c("a" = 1, "b" = 2)
bind_rows(vec)
#> # A tibble: 1 x 2
#> a b
#> <dbl> <dbl>
#> 1 1 2
Run Code Online (Sandbox Code Playgroud)
来自https://cran.r-project.org/web/packages/dplyr/news.html的引用解释了这一变化:
bind_rows()并且bind_cols()现在接受的载体.前者将它们视为行,后者将列视为列.行需要内部名称c(col1 = 1, col2 = 2),而列需要外部名称:col1 = c(1, 2).列表仍被视为数据框,但可以明确拼接!!!,例如bind_rows(!!! x)(#1676).
通过此更改,它意味着用例示例中的以下行:
txt %>% map(read_xml) %>% map(xml_attrs) %>% map_df(~t(.) %>% as_tibble)
可以改写为
txt %>% map(read_xml) %>% map(xml_attrs) %>% map_df(bind_rows)
这也相当于
txt %>% map(read_xml) %>% map(xml_attrs) %>% { bind_rows(!!! .) }
以下示例演示了不同方法的等效性:
library(tidyverse)
library(rvest)
txt <- c('<node a="1" b="2"></node>',
'<node a="1" c="3"></node>')
temp <- txt %>% map(read_xml) %>% map(xml_attrs)
# x, y, and z are identical
x <- temp %>% map_df(~t(.) %>% as_tibble)
y <- temp %>% map_df(bind_rows)
z <- bind_rows(!!! temp)
identical(x, y)
#> [1] TRUE
identical(y, z)
#> [1] TRUE
z
#> # A tibble: 2 x 3
#> a b c
#> <chr> <chr> <chr>
#> 1 1 2 <NA>
#> 2 1 <NA> 3
Run Code Online (Sandbox Code Playgroud)
惯用的方法是!!!在tibble()调用中拼接向量,以便命名的向量元素成为列定义:
library(tibble)
vec <- c("a" = 1, "b" = 2)
tibble(!!!vec)
#> # A tibble: 1 x 2
#> a b
#> <dbl> <dbl>
#> 1 1 2
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v0.3.0)于 2019 年 9 月 14 日创建