0

I have a list like this:

l1 <- list(c("1", "A"), c("2", "B"), c("3", "C"))

and I want to create a dataframe out of it, where the first values of the respective lists are the values for the first column, and the second for the second column, so my desired output is:

col1 col2
-----------
 1    A
 2    B
 3    C

However, When I do

data.frame(l1), I get the rows as columns:

col1 col2 col3
---------------
 1    2    3
 A    B    C

In the documentation for the data.frame function, I was not able to find a respective parameter for this. How do I get the dataframe in the desired format?

bk_
  • 751
  • 1
  • 8
  • 27
  • `library(data.table); setDT(transpose(l1))[]`. – A5C1D2H2I1M1N2O1R2T1 Dec 09 '20 at 17:55
  • 1
    Does this answer your question? It says tidyverse, but there are other solutions shown as well. [Tidyverse approach to binding unnamed list of unnamed vectors by row - do.call(rbind,x) equivalent](https://stackoverflow.com/questions/61614900/tidyverse-approach-to-binding-unnamed-list-of-unnamed-vectors-by-row-do-callr) –  Dec 09 '20 at 18:05
  • I could probably also use the approach that is described there, though I prefer @DaveArmstrongs solution, as it provides a one-line solution to my rather simple question and I was not explicitly asking for a tidyverse approach. Therefore I do not think that my question is an exact duplicate. – bk_ Dec 10 '20 at 09:30

2 Answers2

1

This should do it:

library(magrittr)
do.call(rbind, l1) %>% as.data.frame() %>% setNames(c("col1", "col2")) 
#   col1 col2
# 1    1    A
# 2    2    B
# 3    3    C


DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
  • 1
    Does this need the `tidyverse` attached? –  Dec 09 '20 at 18:06
  • 1
    Only for the pipes, the other functions are base R functions. It's essentially the same as solution as Duck's, but using pipes instead of a single inline function. So you could load `magrittr` or `dplyr` instead if you like. – DaveArmstrong Dec 09 '20 at 18:12
  • 2
    Ah right I overlooked that. I would suggest just an edit to use `magrittr` then. Loading the entire `tidyverse` just for the pipe is a bit much. –  Dec 09 '20 at 18:14
0

Try this:

#Code
res <- setNames(do.call(rbind,lapply(l1, function(x) as.data.frame(t(x)))),c('col1','col2'))

Output:

  col1 col2
1    1    A
2    2    B
3    3    C
Duck
  • 39,058
  • 13
  • 42
  • 84