我正在使用summarytools中的freq()命令循环一些频率表并打印结果。这样做时,我注意到当我尝试保存没有缺失值的 freq() 对象并将其转换为数据框时,总观测值仍然保留缺失值。
# Create a vector with 10 observations of "smoker"
smoker <- c("yes", "no", "yes", NA, NA, NA, "yes", "no", "yes", "no")
# Create a DataFrame using the vector
df <- data.frame(smoker)
library(summarytools)
library(dplyr)
# Create a frequency table without missing values
freq(df$smoker, report.nas = FALSE)
# Try to save this table into a data frame
table <- as.data.frame(freq(df$smoker, report.nas = FALSE)) # OR
table <- df %>% freq(smoker, report.nas = FALSE) %>% as.data.frame()
table
结果应如下所示(排除缺失值,n=7):
Freq % % Cum.
no 3 42.86 42.86
yes 4 57.14 100.00
Total 7 100.00 100.00
但是将其保存到 data.frame 后,它看起来像这样(缺失值添加回来,总数 n=10):
Freq % Valid % Valid Cum. % Total % Total Cum.
no 3 42.85714 42.85714 30 30
yes 4 57.14286 100.00000 40 70
<NA> 3 NA NA 30 100
Total 10 100.00000 100.00000 100 100
这似乎是一个错误,但不确定这是否是预期的结果。关于如何将此输出保存为 data.frame 有什么想法吗?我希望循环数据框并添加 kable 样式。
使用
report.nas
仅影响NA
值的打印,而不影响它们的存储。如果我们将
freq
对象存储为 see
:
see <- summarytools::freq(df$smoker, report.nas = FALSE)
您可以看到它打印所需的值:
但它存储它们与
NA
值:
因此,您仍然需要进行子集化才能获得所需的内容,这种方法只是在有效百分比列上使用
!is.na()
:
want <- as.data.frame(see[!is.na(see[,2]),])
# Freq % Valid % Valid Cum. % Total % Total Cum.
# no 3 42.85714 42.85714 30 30
# yes 4 57.14286 100.00000 40 70
# Total 10 100.00000 100.00000 100 100