Re: [R] pivot table in R

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Tue, 29 Jan 2008 14:40:51 +0000 (UTC)

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
______________________________________________ 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.
Received on Tue 29 Jan 2008 - 14:45:00 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 29 Jan 2008 - 15:30:08 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive