[R] working with tables -- was Re: Mode (statistics) in R?

Charles C. Berry cberry at tajo.ucsd.edu
Tue Jan 27 17:55:30 CET 2009



Carl,

If I understand your drift below, I think this might be what you are after

 	Reduce( c , rev(split(tbag, tbag ) ) , accumulate =TRUE )

or maybe just

 	Reduce( c , rev(split(tbag, tbag ) ) )

which is the same as

 	sort( tbag, decreasing = TRUE )

for many purposes.

HTH,

Chuck

Note that f in  split( x, f ) is a factor, so tbag gets coerced to such.

On Mon, 26 Jan 2009, Carl Witthoft wrote:

> Ok, so I'm slowly figuring out what a factor is, and was able to follow
> the related thread about finding a mode by using constructs like
>
> my_mode = as.numeric(names(table(x))[which.max(table(x))])
>
>
> Now, suppose I want to keep looking for other modes?  For example,
>
> Rgames>  sample(seq(1,10),50,replace=TRUE)->bag
> Rgames>  bag
> [1]  2  8  8 10  7  3  2  9  8  3  8  9  6  6 10 10  7  1
> [19]  9  5  4  3  3  5 10  3  6  3  2  8  4  2  1 10  6  2
> [37]  6  6  9  8  6  8  8  4  3  6  3  9  5  1
> Rgames>  names(which.max(table(bag)))
> [1] "3"
>
> I can then do
>
> Rgames> bag2<-bag[bag!=3]
>
> and repeat the which.max stuff.
> I came up with the following command to find the actual magnitude of the 
> mode:
>
> Rgames>  table(bag)->tbag
> Rgames>  tbag
> bag
>  1  2  3  4  5  6  7  8  9 10
>  3  5  8  3  3  8  2  8  5  5
>
> Rgames>  tbag[dimnames(tbag)$bag=="3"]->bagmode
> Rgames>  bagmode
> 3
> 8
>
>
> Related to this, since bag2 is now bereft of threes,
> Rgames>  table(bag2)
> bag2
>  1  2  4  5  6  7  8  9 10
>  3  5  3  3  8  2  8  5  5
>
> I was able to make the same table with
>
> Rgames>  newtable<-tbag[c(dimnames(tbag)$bag)!="3"]
> Rgames>  newtable
> bag
>  1  2  4  5  6  7  8  9 10
>  3  5  3  3  8  2  8  5  5
>
>
> Is there a cleaner syntax to do these things?
>
> Thanks for your help--and feel free to point me to the Inferno or other paper 
> on the philosophy and use of factors and tables.
>
> Carl
>
> ______________________________________________
> 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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901




More information about the R-help mailing list