簡體   English   中英

tidyverse - 將命名向量轉換為 data.frame/tibble 的首選方法

[英]tidyverse - prefered way to turn a named vector into a data.frame/tibble

經常使用tidyverse ,我經常面臨將命名向量轉換為data.frame / tibble的挑戰,其中列是向量的名稱。
這樣做的首選/tidyversey 方式是什么?
編輯:這與: thisthis github-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 (在dplyr 0.7.0引入)直接支持bind_rows

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的引言解釋了這一變化:

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

慣用的方法是將矢量與!!!拼接在一起。 tibble()調用中,因此命名的矢量元素成為列定義:

library(tibble)
vec <- c("a" = 1, "b" = 2)
tibble(!!!vec)
#> # A tibble: 1 x 2
#>       a     b
#>   <dbl> <dbl>
#> 1     1     2

reprex軟件包 (v0.3.0)創建於2019-09-14

有趣的是,您可以將as_tibble()方法用於列表,以在一次調用中執行此操作。 請注意,這不是最佳做法,因為這不是導出方法。

tibble:::as_tibble.list(vec)
as_tibble(as.list(c(a=1, b=2)))

這對我c("a" = 1, "b" = 2) %>% t() %>% tbl_df()c("a" = 1, "b" = 2) %>% t() %>% tbl_df()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM