Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set R to include missing data – How can is set the `useNA="ifany"` option for `table()` as default?

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)
}
like image 409
Rico Avatar asked Feb 12 '14 09:02

Rico


1 Answers

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.

like image 50
Konrad Rudolph Avatar answered Sep 23 '22 05:09

Konrad Rudolph