查詢 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"

更新於:2021年11月3日

瀏覽量 1K+

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.