查找 R 数据框列值中唯一配对组合。
为了找到 R 数据框列值中唯一配对组合,我们可以结合使用 `combn` 函数和 `unique` 函数。
例如,如果我们有一个名为 `df` 的数据框,其中包含一个名为 `x` 的列,那么我们可以使用下面给出的命令来查找所有列值的唯一配对组合:
combn(unique(df$x),2,FUN=paste,collapse=' ')
示例 1
下面的代码片段创建一个示例数据框:
Grp<-sample(c("I","II","III"),20,replace=TRUE)
df1<-data.frame(Grp)
df1创建了以下数据框:
Grp 1 II 2 III 3 I 4 I 5 II 6 I 7 II 8 III 9 III 10 I 11 I 12 I 13 I 14 II 15 III 16 II 17 I 18 II 19 II 20 III
为了在上面创建的数据框中查找 `df1` 的 `Grp` 列中的值的唯一配对组合,请将以下代码添加到上面的代码片段中:
Grp<-sample(c("I","II","III"),20,replace=TRUE)
df1<-data.frame(Grp)
combn(unique(df1$Grp),2,FUN=paste,collapse=' ')输出
如果您将上面给出的所有代码片段作为一个程序执行,它将生成以下输出:
[1] "II III" "II I" "III I"
示例 2
下面的代码片段创建一个示例数据框:
Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE)
df2<-data.frame(Class)
df2创建了以下数据框:
Class 1 Second 2 Fourth 3 Fourth 4 Second 5 Fourth 6 Third 7 Fourth 8 Third 9 First 10 Fifth 11 Second 12 Second 13 Third 14 Second 15 First 16 Second 17 Fourth 18 First 19 Fifth 20 First
为了在上面创建的数据框中查找 `df2` 的 `Class` 列中的值的唯一配对组合,请将以下代码添加到上面的代码片段中:
Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE)
df2<-data.frame(Class)
combn(unique(df2$Class),2,FUN=paste,collapse=' ')输出
如果您将上面给出的所有代码片段作为一个程序执行,它将生成以下输出:
[1] "Second Fourth" "Second Third" "Second First" "Second Fifth" [5] "Fourth Third" "Fourth First" "Fourth Fifth" "Third First" [9] "Third Fifth" "First Fifth"
示例 3
下面的代码片段创建一个示例数据框:
Category<-sample(c("Extra Small","Small","Medium","Large","Extra Large"),20,replace=TRUE)
df3<-data.frame(Category)
df3创建了以下数据框:
Category 1 Large 2 Extra Small 3 Extra Small 4 Small 5 Large 6 Extra Small 7 Medium 8 Large 9 Large 10 Extra Large 11 Extra Small 12 Extra Small 13 Extra Small 14 Extra Large 15 Large 16 Extra Small 17 Large 18 Medium 19 Extra Large 20 Extra Large
为了在上面创建的数据框中查找 `df3` 的 `Category` 列中的值的唯一配对组合,请将以下代码添加到上面的代码片段中:
Category<-sample(c("Extra Small","Small","Medium","Large","Extra Large"),20,replace=TRUE)
df3<-data.frame(Category)
combn(unique(df3$Category),2,FUN=paste,collapse=' ')输出
如果您将上面给出的所有代码片段作为一个程序执行,它将生成以下输出:
[1] "Large Extra Small" "Large Small" [3] "Large Medium" "Large Extra Large" [5] "Extra Small Small" "Extra Small Medium" [7] "Extra Small Extra Large" "Small Medium" [9] "Small Extra Large" "Medium Extra Large"
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP