[英]Comprehensive matching across a list of vectors
我試圖在所有可用的向量組合之間進行匹配。
例如,我有 4 個向量:
a<-c(1,2,3,4)
b<-c(1,2,6,7)
c<-c(1,2,8,9)
d<-c(3,6,8,2)
預期的輸出應該能夠告訴我:
R 是否具有進行此類比較/匹配的功能?
為簡單起見,向量的數量現在設置為 4。 事實上,我正在處理 100 個向量,並希望在所有可能的向量組合之間進行匹配/相交/比較。 例如,對於 4 個向量,可能有 4C2+4C3+4C4=11 種可用組合。 對於 100 個向量,可能有 100C100+ 100C99+100C98+...+100C2 可用組合
提前致謝
intersect
似乎做你想做的。 它一次只處理成對的向量,例如
intersect(a, b) # 1 2
intersect(b, intersect(c, d)) # 2
如果你想要一個速記相交超過 2,試試Reduce
( ?Reduce
)
# intersection of a/b/c/d
Reduce(intersect, list(a, b, c, d), a)
# intersection of b/c/d
Reduce(intersect, list(b, c, d), b)
Reduce
將依次將intersect
應用到列表和前一個 intersect 調用的結果,從intersect(b, b)
(我剛剛設置為要相交的向量之一的init
參數,因為集合與自身的交集是集)。
如果您想要一種方法來遍歷 (a, b, c, d) 的所有(對、元組、四元組)並返回交集,您可以嘗試
生成長度為 2(對)、3(元組)、4(四元組)的 (a, b, c, d) 的所有組合
combos = lapply(2:4, combn, x=c('a', 'b', 'c', 'd'), simplify=F) # [[1]] # [[1]][[1]] # [1] "a" "b" # [[1]][[2]] # [1] "a" "c" # ... # [[2]] # [[2]][[1]] # [1] "a" "b" "c" # [[2]][[2]] # [1] "a" "b" "d" # ... # [[3]] # [[3]][[1]] # [1] "a" "b" "c" "d"
將其展平為字符向量列表
combos = unlist(combos, recursive=F) # [[1]] # [1] "a" "b" # ... # [[10]] # [1] "b" "c" "d" # [[11]] # [1] "a" "b" "c" "d"
對於每個集合,調用上面指定的Reduce
。 我們可以使用(例如) get("a")
來獲取變量a
; 或mget(c("a", "b", "c")
以獲取列表中的變量a
, b
, c
。如果您的變量是數據框中的列,那么您可以進行適當的修改。
intersects = lapply(combos, function (varnames) { Reduce(intersect, mget(varnames, inherits=T), get(varnames[1])) }) # add some labels for clarity. # You will probably actually want to /do/ something with the # resulting intersections rather than this. names(intersects) <- sapply(combos, paste, collapse=", ") intersects # $`a, b` # [1] 1 2 # $`a, c` # [1] 1 2 # ... # $`a, b, c, d` # [1] 2
您需要修改以適應 R 中的數據; 例如,數據框的列與工作區中的命名向量等等。 您可能也更喜歡從第 3 步開始的for
循環,而不是所有的*apply
具體取決於您想對結果做什么。 (另外,如果你有很多向量,在內存中同時保存所有的交點可能不是一個好主意)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.