[R] Showing NAs when using table()

David Kane dave at kanecap.com
Wed May 23 17:39:49 CEST 2007


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)
>



More information about the R-help mailing list