【问题标题】:Can I use prop.table(table(data$variable)) to get percentages in R?我可以使用 prop.table(table(data$variable)) 在 R 中获取百分比吗?
【发布时间】:2019-05-24 04:37:08
【问题描述】:

我在某处读到我可以在 R 中使用 prop.table(table()) 以获得比例表。但是,我得到的结果与我的手动计算有所不同(即查看 table() 然后除以 NROW()。)我确信我可能在计算中犯了手动错误,但我想确保使用 prop.table(table()) 在逻辑上没有问题。

我正在处理按性别分列的调查数据,这些数据已针对每种性别分为两个单独的数据集(即女性

scoreWomen <- c('a', 'a', 'a', 'b', 'c', 'c', 'd', 'd', 'd', 'd', 'd', 'e', 'e')
scoreMen <- c('a', 'b', 'b', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'e')
prop.table(table(scoreWomen))

#a          b          c          d          e 
#0.23076923 0.07692308 0.15384615 0.38461538 0.15384615 

table(scoreWomen)
#a b c d e 
#3 1 2 5 2 
NROW(scoreWomen)
#13

在小规模测试中,如上面的代码,手动计算与 prop.table(table()) 的结果相同。但是,当我将它们与我的实际数据一起使用时,它们有很大的不同,并且相差几个百分点。为什么会这样?我对 prop.table() 或 NROW() 有什么误解吗?

【问题讨论】:

  • 您的数据集中是否有NA 元素。在这种情况下,表可能会删除它,否则您已指定 useNA = 'always'

标签: r percentage


【解决方案1】:

如果数据集中有 NA 元素,则值可能会有所不同

scoreWomen <- c(scoreWomen, NA)
prop.table(table(scoreWomen))
#scoreWomen
#         a          b          c          d          e 
#0.23076923 0.07692308 0.15384615 0.38461538 0.15384615 

table(scoreWomen)/NROW(scoreWomen)
#scoreWomen
#         a          b          c          d          e 
#0.21428571 0.07142857 0.14285714 0.35714286 0.14285714 

但是,可以通过在table中指定useNA = 'always'来防止

prop.table(table(scoreWomen, useNA = 'always'))
#scoreWomen
#        a          b          c          d          e       <NA> 
#0.21428571 0.07142857 0.14285714 0.35714286 0.14285714 0.07142857 

现在,它与 NROW 的计算值匹配,然后从表输出中删除 &lt;NA&gt; 元素

所以,这完全取决于是否需要通过删除NA元素来进行计算。 NROW 不区分 NA 的出现

【讨论】:

    猜你喜欢
    • 2014-12-14
    • 2017-12-27
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    相关资源
    最近更新 更多