confused_programmer
confused_programmer

Reputation: 103

Convert data from list like data.frame to matrix like data.frame?

I would like to convert data from a list like form to a matrix like form.

My data looks like the following:

dataFrame.list

     compound    time    concentration
1    compA        1       0.5
2    compA        2       0.3
3    compB        2       0.7
4    compB        3       0.8
5    compA        3       0.5
6    compC        1       0.4
7    compC        3       0.1

I would like to get it in the following form:

     compound    time1     time2     time3
1    compA        0.5       0.3       0.5
2    compB        NA        0.7       0.8
3    compC        0.4       NA        0.1

I am having a couple of issues:

dataframe.matrix

  1. Constructing the new empty dataframe
  2. Addressing the the correct column using a variable name.

This is what I have so far:

# uniqe list of compounds
uniqueCompoundList <- unique(dataFrame.list$compound)


# unique vector of times
compoundTime <- as.character(sort(unique(dataFrame.list$time)))


# new matrix like dataframe (This doesn't work but kind of shows what I would like)
dataframe.matrix <- data.frame("compound", compoundTime)

for (singleCompound in uniqueCompoundList){

   # subset based on name
   singeCompoundData <- subset(dataFrame.list, compound == singleCompound)

   # put name in new matrix
   dataframe.matrix$compound <- compound

   for (time in singleCompound$time)){

     # put the value of concentration under the column equal to time
     dataframe.matrix$time <- singleCompound$concentration
   }

}

Upvotes: 1

Views: 42

Answers (1)

akrun
akrun

Reputation: 887481

We can use dcast

library(reshape2)
dcast(df1, compound ~paste0("time", time))
#   compound time1 time2 time3
#1    compA   0.5   0.3   0.5
#2    compB    NA   0.7   0.8
#3    compC   0.4    NA   0.1

Or with xtabs from base R

xtabs(concentration~compound + time, df1)

Upvotes: 1

Related Questions