Skip to content
Back to formatted view

Raw Message

Message-ID: <CADX6M3r=2jUGY0n41swRyP=M-POosTgfkHygWDgH1E66XH453Q@mail.gmail.com>
Date: 2013-07-31T21:58:19Z
From: Shaun Jackman
Subject: Convert rbind of lists to data.frame

I'm trying to build a data.frame row-by-row like so:

df <- data.frame(rbind(list('a',1), list('b', 2), list('c', 3)))

I was surprised to see that the columns of the resulting data.frame
are stored in lists rather than vectors.

str(df)
'data.frame': 3 obs. of  2 variables:
 $ X1:List of 3
  ..$ : chr "a"
  ..$ : chr "b"
  ..$ : chr "c"
 $ X2:List of 3
  ..$ : num 1
  ..$ : num 2
  ..$ : num 3

The desired result is:

str(df)
'data.frame': 3 obs. of  2 variables:
 $ X1: chr  "a" "b" "c"
 $ X2: num  1 2 3

The following works, but is rather ugly:

df <- data.frame(lapply(data.frame(rbind(list('a',1), list('b', 2),
list('c', 3))), unlist))

Thanks,
Shaun