Skip to content

drop zero slots from table?

6 messages · William Dunlap, Sam Steingold

#
I find myself doing
--8<---------------cut here---------------start------------->8---
tab <- table(...)
tab <- tab[tab > 0]
tab <- sort(tab,decreasing=TRUE)
--8<---------------cut here---------------end--------------->8---
all the time.
I am wondering if the "drop 0" (and maybe even sort?) can be effected by
some magic argument to table() which I fail to discover in the docs?
Obviously, I could use droplevels() to avoid 0 counts in the first
place, but I do not want to drop the levels in the data.
#
Function
--8<---------------cut here---------------start------------->8---
sorted.table <- function (vec) {
  tab <- table(vec)
  tab <- tab[tab > 0]
  sort(tab, decreasing=TRUE)
}
--8<---------------cut here---------------end--------------->8---
does what I want but it prints "vec" instead of the name of its
argument:
--8<---------------cut here---------------start------------->8---
vec
  A  B
  10 3
--8<---------------cut here---------------end--------------->8---
how do I pass all arguments of sorted.table() on to table() as is?
thanks!

  
    
#
Here is one way:
+    tab <- table(x)
+    names(dimnames(tab)) <- name
+    tab <- tab[tab > 0]
+    sort(tab, decreasing=TRUE)
+ }
digits
0 8 2 6 4 5
9 4 3 2 1 1
DigitsColumn
0 8 2 6 4 5
9 4 3 2 1 1
My Digits
0 8 2 6 4 5
9 4 3 2 1 1

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
cool, thanks!
Still, I wonder if there is a way to pass all args as is from a function
downward (like in a lisp macro); something like

sorted.table <- function (...) { tab <- table(...); ... }

  
    
#
Why don't you try that and tell us if it works?

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
Because in my wildest dreams it did not occur to me that this could be
valid code in any programming language.
It appears to be valid R, which seems to be out-perling Perl at every turn.
However, it does not do what I want: it does not result in the right
name for the returned table.

Thanks a lot for your insight!