gfa2001
gfa2001

Reputation: 277

How to include NA data in a table

I've recently been using the package tab in R to build frequency tables. The default output of the tabfreq() or the tabmulti() functions excludes NA values. How do I include NA values in their outputs?

Upvotes: 20

Views: 65457

Answers (2)

coip
coip

Reputation: 1520

The table() function in base R can display missing values (i.e. NAs) via useNA, which takes several arguments: "no", "ifany", or "always".

data(airquality) # loads the built-in data frame, which has NAs
table(airquality$Ozone, useNA = "always") # always displays the number of missing values
table(airquality$Wind, useNA = "ifany") # only displays the number of missing values if there are some

Upvotes: 37

Marco Sandri
Marco Sandri

Reputation: 24272

A possible solution:

library(tab)
library(Hmisc)
data(d)

# NA was treated as a third level
Sex <- factor(d$Sex, exclude=NULL)
freqtable2 <- tabfreq(x = d$Group, y = Sex)
print.char.matrix(freqtable2, col.names=T)

+----------+-----------------+-----------------+-------------------+------+
| Variable |Overall (n = 300)|Control (n = 136)|Treatment (n = 164)|   P  |
+----------+-----------------+-----------------+-------------------+------+
|Sex, n (%)|                 |                 |                   |<0.001|
+----------+-----------------+-----------------+-------------------+------+
|    Female|    155 (51.7)   |    93 (68.4)    |     62 (37.8)     |      |
+----------+-----------------+-----------------+-------------------+------+
|      Male|    142 (47.3)   |    43 (31.6)    |     99 (60.4)     |      |
+----------+-----------------+-----------------+-------------------+------+
|        NA|       3 (1.0)   |      0 (0.0)    |       3 (1.8)     |      |
+----------+-----------------+-----------------+-------------------+------+

Upvotes: 4

Related Questions