R语言 如何在表中包含NA数据

ruarlubt  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(164)

我最近一直在使用R中的tab包来构建频率表。tabfreq()tabmulti()函数的默认输出不包括NA值。我如何在它们的输出中包括NA值?

rjee0c15

rjee0c151#

base R中的table()函数可以通过useNA显示缺失值(即NA),它接受几个参数:“no”,“ifany”或“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

字符串

piok6c0g

piok6c0g2#

一个可能的解决方案:

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

字符串

相关问题