mac
mac

Reputation: 165

Coverting a data frame to matrix in R

I would like to convert a data frame to a matrix in R, as in the following example:

df
row.index   column.index   matrix element
1           1              A
1           2              B
2           1              C
2           2              D

matrix
A  B
C  D

Is it possible to do the same with rownames? In example

df
row.name   column.name   matrix element
X          P             A
X          Q             B
Y          P             C
Y          Q             D

matrix
     P  Q

X    A  B
Y    C  D

Thanks for help!

Upvotes: 3

Views: 144

Answers (1)

akrun
akrun

Reputation: 887971

We can use tapply

tapply(df$matrixelement, df[1:2], FUN = I)

It would also work for the second dataset

res <- tapply(df1$matrixelement, df1[1:2], FUN = I)
names(dimnames(res)) <- NULL
res
#   P   Q  
#X "A" "B"
#Y "C" "D"

If we need a data.frame, then dcast can be used

library(reshape2)
dcast(df, row.index ~column.index)

data

df <- structure(list(row.index = c(1L, 1L, 2L, 2L), column.index = c(1L, 
2L, 1L, 2L), matrixelement = c("A", "B", "C", "D")), .Names = c("row.index", 
"column.index", "matrixelement"), class = "data.frame", row.names = c(NA, 
-4L))

df1 <- structure(list(row.name = c("X", "X", "Y", "Y"), column.name = c("P", 
"Q", "P", "Q"), matrixelement = c("A", "B", "C", "D")), .Names = c("row.name", 
"column.name", "matrixelement"), class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 4

Related Questions