[R] Convert rbind of lists to data.frame

Shaun Jackman sjackman at gmail.com
Wed Jul 31 23:58:19 CEST 2013


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



More information about the R-help mailing list