3

I have a list of vectors that I would like to convert into a dataframe.

Code

a <- list( c(1,2,3,4), 
           c(1,2,3,4), 
           c(4,5,6,3), 
           c(6,3,2,6))

With help of this post, I was able to do so in the following manner:

library(tidyverse)
a %>% 
   reduce(rbind) %>% 
   as.data.frame()

> a %>% reduce(rbind) %>% as.data.frame()
      V1 V2 V3 V4
out    1  2  3  4
elt    1  2  3  4
elt.1  4  5  6  3
elt.2  6  3  2  6

I would like to use purrr's bind_rows() function (a %>% bind_rows), as it seems more convenient. However, this generates an error:

Error: Argument 1 must have names.

Questions

  1. What is happening here?
  2. How can I prevent it from happening ;) ?
user213544
  • 2,046
  • 3
  • 22
  • 52
  • 1
    Maybe base: `do.call(rbind, a)` – zx8754 Jul 13 '20 at 10:21
  • 1
    `bind_rows()` is originally a `dplyr` function and is designed to bind together `data.frame`s or `tibble`s. Since `data.frame` columns have names, `bind_rows` expect the input to be named, thats why you get an error. `rbind` is less strict here. – TimTeaFan Jul 13 '20 at 10:27

1 Answers1

2

One option could be:

map_dfr(a, ~ set_names(.x, paste0("V", seq_along(.x))))

     V1    V2    V3    V4
  <dbl> <dbl> <dbl> <dbl>
1     1     2     3     4
2     1     2     3     4
3     4     5     6     3
4     6     3     2     6
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
  • Getting same error? (Maybe version issue: R version 3.6.2; tidyverse_1.3.0) – zx8754 Jul 13 '20 at 10:22
  • @zx8754 yes, with `bind_rows(a)` I get the same error as the OP. – tmfmnk Jul 13 '20 at 10:24
  • 1
    There is no need to use `purrr`'s `map()`: `a %>% set_names(., c("V1", "V2", "V3", "V4")) %>% bind_rows`. – TimTeaFan Jul 13 '20 at 10:24
  • @TimTeaFan `set_names()` is actually from `purrr` :) In addition, your solution is binding the opposite way as desired. – tmfmnk Jul 13 '20 at 10:26
  • @tmfmnk It works very well! Just for my understanding: what does the `~` actually do? – user213544 Jul 13 '20 at 10:33
  • @tmfmnk you are right, without `map` `set_names()` is naming the list elements and not the vectors, which is why my approach transposes the matrix. `set_names()` however, is originally from `rlang`. – TimTeaFan Jul 13 '20 at 10:34