【问题标题】:How to sort factor levels in a table output in R?如何在R中的表格输出中对因子水平进行排序?
【发布时间】:2014-05-16 18:55:44
【问题描述】:

假设我有两个二进制变量:

group <- rbinom(100,1,0.6)
y <- rbinom(100,1,0.3)

table(group,y)
         y
    group  0  1
        0 26 13
        1 42 19

如何以这种格式列出或排序表格输出:

     y
group  1  0
    0 13 26
    1 19 42

【问题讨论】:

  • 你可以做table(group, y)[1:2, c(2,1)] - 如果你想按某个标准排序,你必须告诉我们那个标准是什么 - 增加前导对角线,左边最小的列,.. .

标签: r sorting r-factor


【解决方案1】:

根据您要解决的更大问题,这些方法中的任何一种都可能会有所帮助。作为参考,这是我最初得到的:

> set.seed(1)
> group<-rbinom(100,1,0.6)
> y<-rbinom(100,1,0.3)
> 
> table(group,y)
     y
group  0  1
    0 28 15
    1 42 15

您可以将y 重新定义为factor,并自行选择因子水平的顺序并然后制表:

> table(group,factor(y,levels=c("1","0")))

group  1  0
    0 15 28
    1 15 42

或者您可以像上面一样运行table,然后然后对输出的列进行排序:

> table(group,y)[,c("1","0")]
     y
group  1  0
    0 15 28
    1 15 42

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 2021-11-14
    • 2011-12-08
    • 2010-11-18
    • 1970-01-01
    相关资源
    最近更新 更多