5

In many cases being aware of missing data is crucial and ignoring them can seriously impair your analysis.

Therefore I'd like to set the useNA = "ifany" as default for table(). Ideally similar to options(stringsAsFactors = FALSE)

I found an ugly hack below, but it must go better and without defining a function.

https://stat.ethz.ch/pipermail/r-help/2010-January/223871.html

tableNA<-function(x) {
  varname<-deparse(substitute(x))
  assign(varname,x)
  tabNA<-table(get(varname),useNA="always")
  names(attr(tabNA,"dimnames"))<-varname
  return(tabNA)
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rico
  • 1,998
  • 3
  • 24
  • 46

1 Answers1

11

Well you do need to define a function1 but you can reuse the existing name (and make the definition much leaner):

table = function (..., useNA = 'ifany') base::table(..., useNA = useNA)

This will make the new functionality available under the old name – but only in your code, so it’s “safe” (i.e. it doesn’t change packages’ use of table).

We use ... to allow arbitrary arguments to be passed, and we give useNA the desired default value of 'ifany'. Inside the function, we just call the “real” table function. But in order to avoid calling ourselves, we specify the namespace in which it’s found: base. And we just pass all the arguments untouched.


1 Just look at the source code of table – it doesn’t query any option in setting the argument, so there can be no way of determining the setting of that argument via an option.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Can you briefly expand what's going on in your code or why this syntax works? – Rico Feb 12 '14 at 11:23
  • Also I suggest `<-` for consistency. – Rico Feb 12 '14 at 11:24
  • @Rico I suggest `=` for consistency. I used to use `<-` until a few weeks ago but there’s really no reason for it. I’ll update the answer with an explanation. – Konrad Rudolph Feb 12 '14 at 11:45
  • Ah I was expecting `{}` but they are implicit. – Rico Feb 12 '14 at 13:37
  • @Rico `{}` in R are used only for one single purpose: to group several expressions and treat them as one. You never need parentheses around a single expression (and indeed I strongly recommend not using them in such case). – Konrad Rudolph Feb 12 '14 at 13:40