![](/img/trans.png)
[英]How can I sort a dataframe by a predetermined order of factor levels in R?
[英]How to sort factor levels in a table output in R?
假設我有兩個二進制變量:
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
根據您嘗試解決的更大問題,這些方法中的任何一種都可能有所幫助。 作為參考,這是我最初得到的:
> 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.