在R中订购xtab BY比例

时间:2016-05-29 22:41:55

标签: r

对于示例数据框:

df <- structure(list(region = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 
                                          2L, 2L, 2L, 2L), .Label = c("a", "b", "c", "d"), class = "factor"), 
                     result = c(1L, 0L, 1L, 1L, 0L, 1L, 0L, 0L, 0L, 1L, 0L), weight = c(0.126, 
                                                                                        0.5, 0.8, 1.5, 5.3, 2.2, 3.2, 1.1, 0.1, 1.3, 2.5)), .Names = c("region", 
                                                                                                                                                       "result", "weight"), row.names = c(NA, 11L), class = "data.frame")


df$region <- factor(df$region)
result <- xtabs(weight ~ region + result, data=df)
result

我想重新排序结果列的1。据我所知(from here),我可以使用顺序:

result <- result[order(result[, 2], decreasing=T),]
result
      result
region   0     1
     b 6.9 3.500
     a 5.8 2.426

然而,这似乎只是以1的数量排序 - 我想要在每个区域使用1的比例(即百分比)。我如何使用顺序(或其他东西)以我想要的方式开发我的xtab。

1 个答案:

答案 0 :(得分:4)

使用prop.table

result[order(prop.table(result,1)[,2], decreasing=TRUE),]
#      result
#region   0     1
#     b 6.9 3.500
#     a 5.8 2.426

prop.table(result,1)给出的地方:

prop.table(result,1)
#      result
#region         0         1
#     a 0.7050814 0.2949186
#     b 0.6634615 0.3365385