[R] from table to matrix

Phil Spector spector at stat.berkeley.edu
Tue Dec 14 22:52:22 CET 2010


Here's one way:

> df = data.frame(Date=rep(LETTERS[1:3],each=3),TIME=rep(letters[1:3],3),Q=1:9)
> df
   Date TIME Q
1    A    a 1
2    A    b 2
3    A    c 3
4    B    a 4
5    B    b 5
6    B    c 6
7    C    a 7
8    C    b 8
9    C    c 9
> mat = matrix(0,3,3,dimnames=list(LETTERS[1:3],letters[1:3]))
> mat[as.matrix(df[,1:2])] = df[,3]
> mat
   a b c
A 1 2 3
B 4 5 6
C 7 8 9

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu

On Tue, 14 Dec 2010, JESSICA [via R] wrote:

>
> I have a table like this:
>
> Date TIME  Q
>
> A     a    1
> A     b    2
> A     c    3
> B     a    4
> B     b    5
> B     c    6
> C     a    7
> C     b    8
> C     c    9
>
> I want use R language to turn it to a matrix like :
>    a  b  c
> A  1  2  3
> B  4  5  6
> C  7  8  9
>
>
> I am new to R , anyone can help? Thanks in advance! have a table like this:
>
> Date TIME  Q
>
> A     a    1
> A     b    2
> A     c    3
> B     a    4
> B     b    5
> B     c    6
>
>
> ______________________________________
> This email was sent by JESSICA (via Nabble)
> Your replies will appear at http://r.789695.n4.nabble.com/from-table-to-matrix-tp3087972p3087972.html
> To receive all replies by email, subscribe to this discussion: http://r.789695.n4.nabble.com/template/NamlServlet.jtp?macro=subscribe_by_code&node=3087972&code=ci1oZWxwQHItcHJvamVjdC5vcmd8MzA4Nzk3MnwtNzg0MjM1NTA4
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list