查找 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
广告