# [R] Turn three Columns into a Matrix?

David Winsemius dwinsemius at comcast.net
Tue Feb 23 23:53:07 CET 2010

```On Feb 23, 2010, at 3:18 PM, Ortiz, John wrote:

> Hi all,
>
> If I have a data frame with 3 columns as follows:
>
>> ta
>
> Species	Depth Counts
> spc_a	120	60
> spc_a	140	140
> spc_b	140	5
> spc_b	150	4
> spc_b	180	10
> spc_c	180	10
> spc_c	190	20
>
> How can I turn it into a dataframe or matrix with this structure?:
>
>
> 	      120	140	140	150	180	180	190
> spc_a      60       0       0       0       0       0       0
> spc_a       0     140      0       0       0       0       0
> spc_b       0       0       5       0       0       0       0
> spc_b       0       0       0       4       0       0       0
> spc_b       0       0       0       0      10       0       0
> spc_c       0       0       0       0       0      10       0
> spc_c       0       0       0       0       0       0       20
>
> I tried with matrify, but this function summarized.
>
> library(labdsv)
> matrify(ta)
>
>      120 140 150 180 190
> spc_a  60 140   0   0   0
> spc_b   0   5   4  10   0
> spc_c   0   0   0  10  20
>
> We are looking by one function similarly to matrify but without
> summary.

Not sure what that last sentence means but here is a a solution to
above request:
+
+ Species	Depth Counts
+ spc_a	120	60
+ spc_a	140	140
+ spc_b	140	5
+ spc_b	150	4
+ spc_b	180	10
+ spc_c	180	10
> tdiag <- diag(ta\$Counts, nrow=nrow(ta), ncol=nrow(ta))
> rownames(tdiag)<-ta\$Species
> colnames(tdiag)<-ta\$Depth
> tdiag
120 140 140 150 180 180 190
spc_a  60   0   0   0   0   0   0
spc_a   0 140   0   0   0   0   0
spc_b   0   0   5   0   0   0   0
spc_b   0   0   0   4   0   0   0
spc_b   0   0   0   0  10   0   0
spc_c   0   0   0   0   0  10   0
spc_c   0   0   0   0   0   0  20
>
>
> Thanks!!
>
> John Ortiz
> Smithsonian Tropical Research Institute
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help