Using the tidyverse
a lot i often face the challenge of turning named vectors into a data.frame
/tibble
with the columns being the names of the vector.
What is the prefered/tidyversey way of doing this?
EDIT: This is related to: this and this github-issue
So i want:
require(tidyverse)
vec <- c("a" = 1, "b" = 2)
to become this:
# A tibble: 1 × 2
a b
<dbl> <dbl>
1 1 2
I can do this via e.g.:
vec %>% enframe %>% spread(name, value)
vec %>% t %>% as_tibble
Usecase example:
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)
Which gives
# A tibble: 2 × 3
a b c
<chr> <chr> <chr>
1 1 2 <NA>
2 1 <NA> 3
bind_rows
does not work instead ofmap_df(~t(.) %>% as_tibble)
. So, until now, I transpose, convert to a data frame with strings staying characters (not factors), and then bind the results together. However, a shortcut for this common task could be nice. – Yoshibind_rows
has been updated to now work in the way you want – Donoghue