tidyverse - 将命名向量转换为 data.frame/tibble 的首选方法

2024-05-21

使用tidyverse我经常面临将命名向量转换为向量的挑战data.frame/tibble列是向量的名称。
执行此操作的首选/tidyverse 方式是什么?
编辑:这与:this https://github.com/hadley/dplyr/issues/1676 and this https://github.com/hadley/purrr/issues/255github 问题

所以我想要:

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(引入于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

这段引言来自https://cran.r-project.org/web/packages/dplyr/news.html https://cran.r-project.org/web/packages/dplyr/news.html解释了这一变化:

bind_rows() and bind_cols()现在接受向量。前者将它们视为行,后者将它们视为列。行需要内部名称,例如c(col1 = 1, col2 = 2),而列需要外部名称:col1 = c(1, 2)。列表仍被视为数据框,但可以显式拼接!!!, e.g. 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

tidyverse - 将命名向量转换为 data.frame/tibble 的首选方法 的相关文章

随机推荐