# [R] Counting

William Dunlap wdunlap at tibco.com
Tue Oct 20 18:09:06 CEST 2009

```> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Peter Ehlers
> Sent: Tuesday, October 20, 2009 8:48 AM
> To: Ashta
> Cc: R help
> Subject: Re: [R] Counting
>
>
>   unch <- aggregate(x2==x1, by = list(x1=x1), FUN = sum)
>   chgd <- aggregate(x2!=x1, by = list(x1=x1), FUN = sum)
>
>   -Peter Ehlers

When I hear 'count' I think first of the table() function.
E.g.,
> d<-data.frame(x1=c(1,1,0,0,0,1,0), x2=c(1,0,1,1,0,1,1))
> with(d, table(x1, x1==x2))

x1  FALSE TRUE
0     3    1
1     1    2
or
> with(d, table(x1, factor(x1==x2,labels=c("Changed","Unchanged"))))

x1  Changed Unchanged
0       3         1
1       1         2
or use dimnames<- to change the labels on the table itself.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com

>
> Ashta wrote:
> > Hi All,
> >
> > Assume that I have the following data set  with two variables and I
> > want count the number of observation with identical values
> and number
> > of time each factor changed from x1 to x2.
> >
> > x1  x2
> >  1    1
> >  1    0
> >  0    1
> >  0    1
> >  0    0
> >  1    1
> >  0    1
> >
> > The output should be
> > x1  changed
> >                       0   3    # has changed 3 times
> >                       1   1    # has changed 1 time
> > x1 unchanged
> >                       0  1    # has unchanged only 1 time
> >                       1  2     # has unchanged 2 times
> >
> > Can someone help me how to do it in R?
> >
> >
> > ______________________________________________
> > R-help at r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
> >
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help