[R] Converting data frame to symmetric matrix

jim holtman jholtman at gmail.com
Wed Jan 7 03:50:42 CET 2009


try this:

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=I(sample(L3, 10, replace=TRUE)))
m.out <- matrix(ncol=10, nrow=10)
m.out[cbind(d$x, d$y)] <- d$fac


On Tue, Jan 6, 2009 at 3:29 AM,  <poastpd at umich.edu> wrote:
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list