[R] Showing NAs when using table()

From: David Kane <dave_at_kanecap.com>
Date: Wed, 23 May 2007 11:39:49 -0400


I want to use table() to show NA values with factor variables. Using the set up from the help page, I have:

> b <- factor(rep(c("A","B","C"), 10))
> d <- factor(rep(c("A","B","C"), 10), levels=c("A","B","C","D","E"))
> is.na(d) <- 3:4
> table(b, d)

   d
b A B C D E
  A 9 0 0 0 0
  B 0 10 0 0 0
  C 0 0 9 0 0
>

All of which is fine. But how can I get table() --- or some other function --- to include the observations which are NA for d? This does not do what I want (although I can see how it does what it is documented to do).

> table(b, d, exclude = NULL)

   d
b A B C D E
  A 9 0 0 0 0
  B 0 10 0 0 0
  C 0 0 9 0 0
>

Note that this dilemma only arises with factor variables. With numeric variables, things work differently.

> a <- c(1, 1, 2, 2, NA, 3); b <- c(2, 1, 1, 1, 1, 1); table(a, b)

   b
a 1 2
  1 1 1
  2 2 0
  3 1 0
> table(a, b, exclude = NULL)

      b
a      1 2

  1 1 1
  2 2 0
  3 1 0
  <NA> 1 0
>

How can I get similar behavior with factor variables?

Thanks,

Dave Kane

> R.version

               _                           
platform       i686-pc-linux-gnu           
arch           i686                        
os             linux-gnu                   
system         i686, linux-gnu             
status                                     
major          2                           
minor          5.0                         
year           2007                        
month          04                          
day            23                          
svn rev        41293                       
language       R                           
version.string R version 2.5.0 (2007-04-23)
>


R-help_at_stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Wed 23 May 2007 - 15:47:41 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 24 May 2007 - 07:31:21 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.