[R] Converting data frame to symmetric matrix

poastpd at umich.edu poastpd at umich.edu
Tue Jan 6 09:29:16 CET 2009


Dear Sir or Madam,

I have the following data frame (which is just a toy example of my  
larger dataset)

L3 <- LETTERS[1:3]
x=c(1,1,2,2,3,3,4,4,5,5)
y=1:10
d <- data.frame(cbind(x,y), fac=sample(L3, 10, replace=TRUE))


This data frame produces the following output

    x  y fac
1  1  1   C
2  1  2   C
3  2  3   B
4  2  4   B
5  3  5   C
6  3  6   B
7  4  7   B
8  4  8   C
9  5  9   B
10 5 10   A


Is there a command I can use to convert data frame d into a 10 X 10  
symmetric matrix where the columns are labeled 1 through 10, the rows  
are labeled 1 through 10, and the entries in each cell are the  
corresponding values of "fac"?

For example, the first two columns and rows should have the following entries:

   1  2
1 C  C

2 C  NA

Any suggestions will be greatly appreciated.

Many thanks,

Paul Poast




More information about the R-help mailing list