[R] How to built a pivot table of value

Berend Hasselman bhh at xs4all.nl
Sat Dec 1 14:50:07 CET 2012


On 01-12-2012, at 13:37, CE.KA wrote:

> Hi R users
> 
> Imagine the table "base":
> p=c("d","d","b","b","a","a")
> q=c("v1","v2","v1","v2","v1","v2")
> r=c(5,2,4,8,9,7)
> base=data.frame(p,q,r)
> base
> 
>     p   q     r
> 1  d   v1   5
> 2  d   v2   2
> 3  b   v1  4
> 4  b   v2   8
> 5  a   v1   9
> 6  a   v2   7
> 
> How programming R to get this result:
> 
>             v1   v2
> a          9        7
> b         4        8
> d         5        2
> 

xtabs(r~p+q,data=base)

Output
---------
   q
p   v1 v2
  a  9  7
  b  4  8
  d  5  2

Berend




More information about the R-help mailing list