[英]Extracting rows from a data frame depending on the combination of values in two colums
[英]extracting unique combination rows from a data frame in R
我有一個數據框,給出了同一個州提供的人的成對相關性。 我給出了一個關於我希望如何處理這些數據的小例子,但是現在我的實際數據集有成對相關的1500萬行和更多的附加列。
以下是示例數據:
>sample_data
Pair_1ID Pair_2ID CORR
1 2 0.12
1 3 0.23
2 1 0.12
2 3 0.75
3 1 0.23
3 2 0.75
我想生成一個沒有重復的新數據幀,例如在第1行中,人1和2之間的相關性是0.12。 第1行與第3行相同,它顯示了2和1之間的相關性。由於它們具有相同的信息,我希望最終文件沒有重復,我想要一個類似下面的文件:
>output
Pair_1ID Pair_2ID CORR
1 2 0.12
1 3 0.23
2 3 0.75
有人可以幫忙嗎? 獨特的命令不適用於此,我不知道該怎么做。
假設每個組合出現兩次:
subset(sample_data , Pair_1ID <= Pair_2ID)
如果不:
unique(transform(sample_data, Pair_1ID = pmin(Pair_1ID, Pair_2ID),
Pair_2ID = pmax(Pair_1ID, Pair_2ID)))
編輯 :關於最后一個,包括unique
CORR
因為可能的浮點問題不是一個好主意。 我也看到你提到你有更多的專欄。 因此,最好將比較限制為兩個ID:
relabeled <- transform(sample_data, Pair_1ID = pmin(Pair_1ID, Pair_2ID),
Pair_2ID = pmax(Pair_1ID, Pair_2ID))
subset(relabeled, !duplicated(cbind(Pair_1ID, Pair_2ID)))
flodel的答案真的很棒。 我只是想在沒有查看實際值的情況下添加基於索引的另一種解決方案。 它僅在所有組合都存在且數據框由第一列第一列和第二列第二列(如示例中)排序時有效。
maxVal <- max(sample_data$Pair_1ID)
shrtIdx <- logical(maxVal)
idx <- sapply(seq(maxVal - 1, 1), function(x) replace(shrtIdx, seq(x), TRUE))
sample_data[idx,]
# Pair_1ID Pair_2ID CORR
# 1 1 2 0.12
# 2 1 3 0.23
# 4 2 3 0.75
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.