R中分类变量的频率分布

Frequency distribution of a categorical variable in R

我正在尝试准备数据中分类变量的频率分布 table,我正在使用以下代码。但是在我查看时输出看起来不错,但在报告中打印不正常。

# These lines are not needed because the data below is already
# in that format
# STI<-STI_IPD1%>% select(Q18_1,Q54)
# STI$Q54<-as.factor(STI$Q54)

STI = structure(list(Q18_1 = c(101L, 120L, 29L, 101L, 94L, 16L, 47L, 
141L, 154L, 47L, 141L, 154L, 154L, 29L, 58L, 154L, 101L, 154L, 
47L, 141L, 75L, 1L, 120L, 16L, 154L, 141L, 141L, 154L, 154L, 
154L, 29L, 141L, 38L, 47L, 101L, 16L, 154L, 154L, 101L, 192L, 
58L, 154L, 16L, 120L, 101L, 1L, 38L, 1L, 154L, 1L, 16L, 58L, 
75L, 154L, 47L, 58L, 120L, 141L, 1L, 141L, 16L, 141L, 58L, 29L, 
101L, 58L, 154L, 75L, 75L, 141L, 29L, 101L, 101L, 154L, 16L, 
101L, 101L, 47L, 47L, 181L, 16L, 154L, 47L, 154L, 47L, 120L, 
75L, 47L, 192L, 1L, 154L, 154L, 120L, 141L, 58L, 47L, 154L, 101L, 
75L, 141L, 75L, 16L, 47L, 1L, 58L, 141L), Q54 = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("", "Discretionary if earnings per share goals are met.", 
"initial funding by targets and as year goes on begin to include financial results", 
"Non-represented are targets focused and budgeted and union plans are self funded based on operating margin achievements."
), class = "factor")), class = c("data.table", "data.frame"), row.names = c(NA, 
-106L), .Names = c("Q18_1", 
"Q54"))

as.data.frame(table(STI$Q54))

还有其他方法可以准备这样的输出吗?

我希望输出每个因子水平的计数 table。一列中的每个因子水平和另一列中的计数。

我正在使用 Rmarkdown 在 word 文件中输出。同样在输出 window 中,输出未打印为两列 table.

要在 Markdown 中将数据框打印为 table,可以使用 knitr 中的 kable() 函数。

library(knitr)
kable(aDataFrame)

例如...

data.frame()kable() 函数是在 R Markdown 中交流表格信息的非常有用的技术。有关使用此技术的几个更复杂的示例,请阅读我的文章 Commentary on ToothGrowth Factorial ANOVA,其中我将 Robert Kabacoff 的分析与 Coursera 上约翰霍普金斯大学统计推理课程的要求进行了比较。

问候,

莱恩

(11/22/2017) 更新: 回应@sandhya-ghildiyal 的评论,这里是如何从 table 输出中排除空白行.如果我们将table()的结果保存到一个对象中,那么我们就可以在kable()函数中使用提取运算符[来排除因子值为1的行,空白space。

theTable <- as.data.frame(table(STI$Q54))
kable(theTable[as.numeric(theTable$Var1) != 1,])