-----Original Message-----
From: Sam Steingold [mailto:sam.steingold at gmail.com] On Behalf Of Sam Steingold
Sent: Wednesday, September 19, 2012 10:48 AM
To: r-help at r-project.org; William Dunlap
Subject: Re: drop zero slots from table?
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(...); ... }
* William Dunlap <jqhaync at gvopb.pbz> [2012-09-19 16:26:08 +0000]:
Here is one way:
sorted.table <- function(x, name = if (is.list(x))names(x) else deparse(substitute(x))[1]) {
+ tab <- table(x)
+ names(dimnames(tab)) <- name
+ tab <- tab[tab > 0]
+ sort(tab, decreasing=TRUE)
+ }
digits <- factor(trunc(100*log2(1:20)%%.1), levels=0:9)
sorted.table(digits)
digits
0 8 2 6 4 5
9 4 3 2 1 1
sorted.table(data.frame(DigitsColumn=digits))
DigitsColumn
0 8 2 6 4 5
9 4 3 2 1 1
sorted.table(digits, name="My Digits")
My Digits
0 8 2 6 4 5
9 4 3 2 1 1
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Of Sam Steingold
Sent: Wednesday, September 19, 2012 9:13 AM
To: r-help at r-project.org
Subject: Re: [R] drop zero slots from table?
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!
* Sam Steingold <fqf at tah.bet> [2012-09-19 11:51:08 -0400]:
I find myself doing
tab <- table(...)
tab <- tab[tab > 0]
tab <- sort(tab,decreasing=TRUE)
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.