[R] Convert rbind of lists to data.frame

2013-07-31 Thread Shaun Jackman
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

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Convert rbind of lists to data.frame

2013-07-31 Thread arun
May be this helps:

l1- list('a',1)
 l2- list('b',2)
 l3- list('c',3)
df1-data.frame(mapply(`c`,l1,l2,l3,SIMPLIFY=FALSE),stringsAsFactors=FALSE)
 colnames(df1)-paste0(X,1:2)
  str(df1)
#'data.frame':    3 obs. of  2 variables:
# $ X1: chr  a b c
# $ X2: num  1 2 3

A.K.



- Original Message -
From: Shaun Jackman sjack...@gmail.com
To: R help r-help@r-project.org
Cc: 
Sent: Wednesday, July 31, 2013 5:58 PM
Subject: [R] 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

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.