user1638221
user1638221

Reputation: 25

How to transform a dataframe in an ordered matrix?

Please, input the following code:

A <- matrix(11, nrow = 4, ncol = 3)
A[,2] <- seq(119, 122, 1)
A[,3] <- seq(45, 42)
B <- matrix(39, nrow = 4, ncol = 3)
B[,2] <- seq(119, 122, 1)
B[,3] <- seq(35, 32)
C <- matrix(67, nrow = 4, ncol = 3)
C[,2] <- seq(119, 122, 1)
C[,3] <- seq(27, 24)

D <- rbind(A, B, C)

You will get D which is a 12 x 3 matrix; I would like to know the most efficient way to obtain Mat starting from D.

> Mat
    11 39 67
119 45 35 27
120 44 34 26
121 43 33 25
122 42 32 24

In fact, Mat is the last column of D indexed by the first and the second column of D; e.g. consider Mat[1,1] which is equal to 45: it comes from the only row of D which is identified by 11 and 119.

How may I obatin it?

Thanks,

Upvotes: 1

Views: 96

Answers (2)

Maiasaura
Maiasaura

Reputation: 32996

library(reshape2)
dcast(data.frame(D), X2 ~ X1)

Upvotes: 2

James
James

Reputation: 66864

You can use xtabs:

xtabs(D[,3]~D[,2]+D[,1])
      D[, 1]
D[, 2] 11 39 67
   119 45 35 27
   120 44 34 26
   121 43 33 25
   122 42 32 24

Upvotes: 3

Related Questions