如何在R语言中查找字符串向量元素的固定大小的唯一组合?
可以使用`combn`函数结合`unique`函数来查找向量元素的唯一组合,`size`参数将帮助我们识别每个组合的大小。例如,如果我们有一个定义为x的包含字符串值的向量,则可以使用`combn(unique(x), 2)`创建大小为2的向量元素的唯一组合。
示例1
x1<−c("A","B","C","A","D","E","A","C") combn(unique(x1),2)
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] "A" "A" "A" "A" "B" "B" "B" "C" "C" "D" [2,] "B" "C" "D" "E" "C" "D" "E" "D" "E" "E"
示例
combn(unique(x1),3)
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] "A" "A" "A" "A" "A" "A" "B" "B" "B" "C" [2,] "B" "B" "B" "C" "C" "D" "C" "C" "D" "D" [3,] "C" "D" "E" "D" "E" "E" "D" "E" "E" "E"
示例
combn(unique(x1),4)
输出
[,1] [,2] [,3] [,4] [,5] [1,] "A" "A" "A" "A" "B" [2,] "B" "B" "B" "C" "C" [3,] "C" "C" "D" "D" "D" [4,] "D" "E" "E" "E" "E"
示例
combn(unique(x1),5)
输出
[,1] [1,] "A" [2,] "B" [3,] "C" [4,] "D" [5,] "E"
示例2
x2<−c("India","Russia","India","USA","USA","UK","Egypt","UK") combn(unique(x2),2)
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] "India" "India" "India" "India" "Russia" "Russia" "Russia" "USA" "USA" [2,] "Russia" "USA" "UK" "Egypt" "USA" "UK" "Egypt" "UK" "Egypt" [,10] [1,] "UK" [2,] "Egypt"
示例
combn(unique(x2),3)
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] "India" "India" "India" "India" "India" "India" "Russia" "Russia" [2,] "Russia" "Russia" "Russia" "USA" "USA" "UK" "USA" "USA" [3,] "USA" "UK" "Egypt" "UK" "Egypt" "Egypt" "UK" "Egypt" [,9] [,10] [1,] "Russia" "USA" [2,] "UK" "UK" [3,] "Egypt" "Egypt"
示例
combn(unique(x2),4)
输出
[,1] [,2] [,3] [,4] [,5] [1,] "India" "India" "India" "India" "Russia" [2,] "Russia" "Russia" "Russia" "USA" "USA" [3,] "USA" "USA" "UK" "UK" "UK" [4,] "UK" "Egypt" "Egypt" "Egypt" "Egypt"
示例
combn(unique(x2),5)
输出
[,1] [1,] "India" [2,] "Russia" [3,] "USA" [4,] "UK" [5,] "Egypt"
示例3
x3<−c("G1","G2","G3","G1","G2","G4","G5","G3","G5","G2") combn(unique(x3),2)
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] "G1" "G1" "G1" "G1" "G2" "G2" "G2" "G3" "G3" "G4" [2,] "G2" "G3" "G4" "G5" "G3" "G4" "G5" "G4" "G5" "G5"
示例
combn(unique(x3),3)
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] "G1" "G1" "G1" "G1" "G1" "G1" "G2" "G2" "G2" "G3" [2,] "G2" "G2" "G2" "G3" "G3" "G4" "G3" "G3" "G4" "G4" [3,] "G3" "G4" "G5" "G4" "G5" "G5" "G4" "G5" "G5" "G5"
示例
combn(unique(x3),4)
输出
[,1] [,2] [,3] [,4] [,5] [1,] "G1" "G1" "G1" "G1" "G2" [2,] "G2" "G2" "G2" "G3" "G3" [3,] "G3" "G3" "G4" "G4" "G4" [4,] "G4" "G5" "G5" "G5" "G5"
示例
combn(unique(x3),5)
输出
[,1] [1,] "G1" [2,] "G2" [3,] "G3" [4,] "G4" [5,] "G5"
示例4
x4<−c("HOT","COLD","SWEET","BITTER","HOT","SWEET") combn(unique(x4),2)
输出
combn(unique(x4),2) [,1] [,2] [,3] [,4] [,5] [,6] [1,] "HOT" "HOT" "HOT" "COLD" "COLD" "SWEET" [2,] "COLD" "SWEET" "BITTER" "SWEET" "BITTER" "BITTER"
示例
combn(unique(x4),3)
输出
[,1] [,2] [,3] [,4] [1,] "HOT" "HOT" "HOT" "COLD" [2,] "COLD" "COLD" "SWEET" "SWEET" [3,] "SWEET" "BITTER" "BITTER" "BITTER"
示例
combn(unique(x4),4)
输出
[,1] [1,] "HOT" [2,] "COLD" [3,] "SWEET" [4,] "BITTER"
广告