在 R 数据框中查找唯一组组合的计数。
要在R数据框中找到唯一组组合的计数,我们可以使用dplyr包的计数功能以及取消分组功能。
例如,如果我们有一个名为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