开发者

Convert table into matrix by column names [duplicate]

开发者 https://www.devze.com 2022-12-17 03:48 出处:网络
This question already has answers here: Reshape three column data frame to matrix ("long" to "wide" format) [duplicate]
This question already has answers here: Reshape three column data frame to matrix ("long" to "wide" format) [duplicate] (6 answers) Closed 5 years ago.

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?


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消