查詢 R 資料框中唯一分組組合的數量。


要查詢 R 資料框中唯一分組組合的數量,我們可以使用 dplyr 包的 count 函式以及 ungroup 函式。

例如,如果我們有一個名為 df 的資料框,其中包含三個分組列,例如 G1、G2 和 G3,那麼我們可以使用以下命令來計算 df 中唯一分組組合的數量:

count(df,G1,G2,G3)%%ungroup()

示例 1

以下程式碼片段建立了一個示例資料框:

Grp1<-sample(1:2,20,replace=TRUE)
Grp2<-sample(1:2,20,replace=TRUE)
Grp3<-sample(1:2,20,replace=TRUE)
df1<-data.frame(Grp1,Grp2,Grp3)
df1

建立了以下資料框

 Grp1 Grp2 Grp3
 1 2   1   1
 2 1   2   1
 3 2   1   2
 4 2   2   1
 5 1   1   1
 6 1   1   2
 7 2   1   1
 8 2   1   2
 9 2   1   2
10 1   1   1
11 2   1   1
12 2   1   1
13 2   2   2
14 2   1   2
15 1   2   2
16 2   2   1
17 2   1   2
18 2   2   1
19 1   1   2
20 2   2   2

要載入 dplyr 包並在上面建立的資料框上計算 df1 中的唯一分組組合,請將以下程式碼新增到上述程式碼片段中:

Grp1<-sample(1:2,20,replace=TRUE)
Grp2<-sample(1:2,20,replace=TRUE)
Grp3<-sample(1:2,20,replace=TRUE)
df1<-data.frame(Grp1,Grp2,Grp3)
library(dplyr)
count(df1,Grp1,Grp2,Grp3)%%ungroup()

輸出

如果您將以上所有程式碼片段作為單個程式執行,則會生成以下輸出:

Grp1 Grp2 Grp3 n
1 1    1   1   2
2 1    1   2   2
3 1    2   1   1
4 1    2   2   1
5 2    1   1   4
6 2    1   2   5
7 2    2   1   3
8 2    2   2   2

示例 2

以下程式碼片段建立了一個示例資料框:

Class1<-sample(c("First","Second","Third"),20,replace=TRUE)
Class2<-sample(c("First","Second","Third"),20,replace=TRUE)
Class3<-sample(c("First","Second","Third"),20,replace=TRUE)
df2<-data.frame(Class1,Class2,Class3)
df2

建立了以下資料框

  Class1  Class2 Class3
 1 First  Second Second
 2 Second Third  Second
 3 Third  Second Third
 4 First  Third  Second
 5 Second Third  First
 6 Second Third  First
 7 First  Second Second
 8 Third  First  Third
 9 Third  Third  Third
10 Second First  Third
11 Third  Second Second
12 Second Second Second
13 Third  Second Second
14 Third  First  Third
15 First  First  First
16 Third  Third  Third
17 Third  Third  Third
18 First  Third  Third
19 Third  Second First
20 Second Second Second

要計算上面建立的資料框上 df2 中的唯一分組組合,請將以下程式碼新增到上述程式碼片段中:

Class1<-sample(c("First","Second","Third"),20,replace=TRUE)
Class2<-sample(c("First","Second","Third"),20,replace=TRUE)
Class3<-sample(c("First","Second","Third"),20,replace=TRUE)
df2<-data.frame(Class1,Class2,Class3)
count(df2,Class1,Class2,Class3)%%ungroup()

輸出

如果您將以上所有程式碼片段作為單個程式執行,則會生成以下輸出:

  Class1  Class2 Class3 n
 1 First  First  First 1
 2 First  Second Second 2
 3 First  Third  Second 1
 4 First  Third  Third 1
 5 Second First  Third 1
 6 Second Second Second 2
 7 Second Third  First 2
 8 Second Third  Second 1
 9 Third  First  Third 2
10 Third  Second First 1
11 Third  Second Second 2
12 Third  Second Third 1
13 Third  Third  Third 3

更新於: 2021年11月10日

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告