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

Marc Schwartz marc_schwartz at me.com
Tue Jul 14 15:04:09 CEST 2009


On Jul 14, 2009, at 7: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().
>
> Thanks in advance.

Read your data in as follows:

# Set the rownames to the values in 'X' and coerce to a matrix
rawData <- as.matrix(read.table("raw_data.txt", header = TRUE,
                                 sep = "\t", row.names = "X"))


# Note that you have 'x3' in your results, but 'x4' was in the
# initial data table, so I kept 'x4'
 > rawData
    A B  C
x1 2 3  4
x2 5 7 10
x4 2 3  5


# Set the row and column names
names(dimnames(rawData)) <- list("cell", "comp")

 > rawData
     comp
cell A B  C
   x1 2 3  4
   x2 5 7 10
   x4 2 3  5


# See ?as.data.frame.table
 > as.data.frame.table(rawData, responseName = "value")
   cell comp value
1   x1    A     2
2   x2    A     5
3   x4    A     2
4   x1    B     3
5   x2    B     7
6   x4    B     3
7   x1    C     4
8   x2    C    10
9   x4    C     5


HTH,

Marc Schwartz




More information about the R-help mailing list