Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert table into matrix by column names [duplicate]

Tags:

r

statistics

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?

like image 456
Mark Avatar asked Jan 24 '10 05:01

Mark


2 Answers

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
like image 192
George Dontas Avatar answered Sep 30 '22 11:09

George Dontas


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
like image 44
Aniko Avatar answered Sep 30 '22 11:09

Aniko