简体   繁体   English

如何在R中的表输出中对因子级别进行排序?

[英]How to sort factor levels in a table output in R?

Suppose I have two binary variables: 假设我有两个二进制变量:

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

How to table out or sort the table output in this format: 如何以这种格式输出或排序表输出:

     y
group  1  0
    0 13 26
    1 19 42

Depending on what bigger problem you are trying to solve, either one of these approaches might be helpful. 根据您尝试解决的更大问题,这些方法中的任何一种都可能有所帮助。 For reference, here is what I get initially: 作为参考,这是我最初得到的:

> 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

You can redefine y to be a factor with your own choice of ordering of the factor levels and then tabulate: 你可以重新定义y是一个factor用自己的因子水平进行排序的选择, 然后制表:

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

group  1  0
    0 15 28
    1 15 42

Or you can run the table as above and then sort the columns of the output: 或者您可以像上面那样运行table然后对输出的列进行排序:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM