[R] How to provide list as an argument for the data.frame()

David Winsemius dwinsemius at comcast.net
Tue Jul 14 14:30:48 CEST 2009


On Jul 14, 2009, at 8:14 AM, Gaurav Kumar wrote:

> Hi R -users,
>
> i've a table as describe below. I'm reading the numeric value  
> presented in this table to populate a list.
>
> #table
> #============
> #X    A    B    C
> #x1    2    3    4
> #x2    5    7    10
> #x4    2    3    5
> #============
>
> rawData <- read.table("raw_data.txt",header=T, sep="\t")
> myList=list()
> counter=0
> for (i in c(1:length(rawData$X)))
> {
>     print (i)
>     myList[counter <- counter +1]=as.numeric(rawData$A[i]);
>     myList[counter <- counter +1]=as.numeric(rawData$B[i]);
>     myList[counter <- counter +1]=as.numeric(rawData$C[i]);
> }
> print(myList)
>
> comp <- factor(rep(c("A","B","C"),c(3,3,3)))
> cell <- factor(rep(c("x1","x2","x3"),3))
>
> t <- data.frame(comp,cell)
> print(t)
>
> i'm looking for the output show below
> #  comp cell value
> #1    A   x1   2
> #2    A   x2   5
> #3    A   x3   2
> #4    B   x1   3
> #5    B   x2   7
> #6    B   x3   3
> #7    C   x1   4
> #8    C   x2   10
> #9    C   x3   5
>
> Help needed as how i should provide list as a third argument to  
> data.frame().


To answer your narrow question:

?unlist


But wouldn't it have been a lot easier to to this, and skip all that C  
style looping?

cbind(cell=factor(rep(c("x1","x2","x3"),3)), stack(rawData) )
###
   cell values ind
1   x1      2   A
2   x2      5   A
3   x3      2   A
4   x1      3   B
5   x2      7   B
6   x3      3   B
7   x1      4   C
8   x2     10   C
9   x3      5   C
>
> Thanks in advance.
>
>
> Gaurav Kumar
> www.gauravkumar.org
>
> PhD Student, Chemistry and Biomolecular Sciences, Macquarie ,  
> Sydney, Australia.
> MS (Computational Biology), NCBS-TIFR, Bangalore, India.
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list