1

我有一些看起来像这样的数据:

          A      B
6     Often  Often
7    Always Always
8    Rarely Rarely
9 Sometimes  Often

structure(list(A = structure(c(5L, 6L, 3L, 4L), .Label = c("", 
"Almost Never", "Rarely", "Sometimes", "Often", "Always"), class = c("ordered", 
"factor")), B = structure(c(5L, 6L, 3L, 5L), .Label = c("", "Almost Never", 
"Rarely", "Sometimes", "Often", "Always"), class = c("ordered", 
"factor"))), .Names = c("A", "B"), row.names = 6:9, class = "data.frame")

使用摘要,我可以根据可能的响应获得每种响应类型的计数,这正是我想要的:

            A                B    
             :0               :0  
 Almost Never:0   Almost Never:0  
 Rarely      :1   Rarely      :1  
 Sometimes   :1   Sometimes   :0  
 Often       :1   Often       :2  
 Always      :1   Always      :1  

现在我想操纵这些数字来获得(经常+总是)/总响应。虽然摘要输出是字符输出——我可以在冒号上拆分,但必须有更好的方法。

给定上面的数据集,我如何计算每个问题的经常 + 总回答的百分比?

4

1 回答 1

1

这可以使用applyand来完成table(假设d是您的数据框):

apply(d, 2, function(col) {
    tab = table(col)
    (tab["Often"] + tab["Always"]) / sum(tab)
})

请注意,仅当每列中始终至少有一个“总是”和一个“经常”时,上述内容才有效。以下内容稍微不简洁,但即使列中缺少“始终”或“经常”也可以使用:

sapply(1:NCOL(d), function(i) {
        tab = table(d[, i])
        (tab["Often"] + tab["Always"]) / sum(tab)
})
于 2013-03-14T14:39:29.073 回答