[R] working with tables -- was Re: Mode (statistics) in R?
Carl Witthoft
carl at witthoft.com
Tue Jan 27 01:50:39 CET 2009
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
More information about the R-help
mailing list