5

I have data frame that looks like the following

       models cores     time
1       4     1 0.000365
2       4     2 0.000259
3       4     3 0.000239
4       4     4 0.000220
5       8     1 0.000259
6       8     2 0.000249
7       8     3 0.000251
8       8     4 0.000258

... etc

I would like to convert it into a table/matrix with #models for rows labels, the #cores for the columns labels and time as the data entries

e.g.

  1 2 3 4 5 6 7 8    
1   time data
4   time data

currently I'm using for loops to convert it into this structure, though I am wondering if there was a better method?

Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142
Mark
  • 3,177
  • 4
  • 26
  • 37

3 Answers3

9

Check method cast from reshape package

# generate test data    
x <- read.table(textConnection('
models cores  time
4 1 0.000365
4 2 0.000259
4 3 0.000239
4 4 0.000220
8 1 0.000259
8 2 0.000249
8 3 0.000251
8 4 0.000258'
), header=TRUE)


library(reshape)
cast(x, models ~ cores)

results:

  models        1        2        3        4
1      4 0.000365 0.000259 0.000239 0.000220
2      8 0.000259 0.000249 0.000251 0.000258
gd047
  • 29,749
  • 18
  • 107
  • 146
  • 1
    It looks like I don't have the package reshape, but I found that this works as well: tapply(f[,3],f[,1:2],c) – Mark Jan 25 '10 at 03:12
6

Here is a version using the base function reshape:

y <- reshape(x, direction="wide", v.names="time", timevar="cores", 
             idvar="models")

with the output

  models   time.1   time.2   time.3   time.4
1      4 0.000365 0.000259 0.000239 0.000220
5      8 0.000259 0.000249 0.000251 0.000258

With the hard work of reshaping done, you can extract the part you want:

res <- data.matrix(subset(y, select=-models))
rownames(res) <- y$models
colnames(res) <- substr(colnames(res),6,7)

And you get the matrix:

         1        2        3        4
4 0.000365 0.000259 0.000239 0.000220
8 0.000259 0.000249 0.000251 0.000258
Aniko
  • 18,516
  • 4
  • 48
  • 45
4

You don't need the reshape package, there's a builtin function reshape which can do it.

> reshape(x,idvar="models",timevar="cores",direction="wide")
  models   time.1   time.2   time.3   time.4
1      4 0.000365 0.000259 0.000239 0.000220
5      8 0.000259 0.000249 0.000251 0.000258
Alex Brown
  • 41,819
  • 10
  • 94
  • 108