[R] pivot table in R

David Winsemius dwinsemius at comcast.net
Tue Jan 29 15:40:51 CET 2008


pietro.parodi at aon.co.uk wrote in
news:OF9469393D.467B36A7-ON802573DF.00412BB7-802573DF.0042657E at aon.co.u
k: 

Three or four solutions have already been offered. Here is (yet) 
another:

> Atxt <- "
+   sex   age region no_of_accidents
+ 1   F young  north              10
+ 2   F young  south              12
+ 3   F   old  north               5
+ 4   F   old  south               7
+ 5   M young  north              24
+ 6   M young  south              30
+ 7   M   old  north              12
+ 8   M   old  south              17"
> 
> A <- read.table(textConnection(Atxt), header=TRUE)

> Asex <- xtabs(no_of_accidents ~ sex, data=A)
> Asex
sex
 F  M 
34 83 

xtabs() returns an object of class = contingency table. This may have 
added advantage if you are using statistical function which expect such 
an object. Using a formula based function also lets you quickly expand 
the analysis.

> Asexreg <- xtabs(no_of_accidents ~ sex+region, data=A)
> Asexreg
   region
sex north south
  F    15    19
  M    36    47

-- 
David Winsemius

> Hello,
> 
> I'm struggling with an elementary problem with R. I have a simple
> data frame such as this one giving the number of accidents
> subdivided by sex, age and region.
> 
> sex     age     region          no_of_accidents
> 
> F       young   north           10
> F       young   south           12
> F       old     north           5
> F       old     south           7
> M       young   north           24
> M       young   south           30
> M       old     north           12
> M       old     south           17
> 
> and I would like to build a pivot table, e.g. obtaining the sum of
> the number of accidents for each sex:
> 
> sex     age     region          no_of_accidents
> 
> F       (any)   (any)           34
> M       (any)   (any)           83



More information about the R-help mailing list