簡體   English   中英

data.table 中組之間項目的交集

[英]Intersection of items between groups in a data.table

我有一個data.table兩列,一用一groupID和其他與一個color 我想找到所有組之間的交集長度或成對交集操作。 網上有類似的帖子,但沒有完全符合我正在尋找的內容。

require(data.table)


set.seed(1)
x <- data.table(
  groupID = paste0(sample(LETTERS), sample(LETTERS, replace = TRUE)),
  color = sapply(1:length(LETTERS), function(x) sample(colors()[1:10])[1:sample(5:10)[1]])
)

x <- x[, .(color = unlist(color)), keyby = groupID]

下表沒有正確的值,但它看起來像這樣:

groups <- x[, .N, keyby = groupID][,groupID]; results <- CJ(groups, groups)
results[, intersectionLength := sapply(1:nrow(results), function(x) sample(5:10)[1])]

編輯

這個帖子有一個類似的問題。 我怎么能把它應用到我的問題上?

這是Map一個選項,用於比較組列的成對元素以提取intersect “顏色”值並獲得它的length

library(data.table)
CJ(group1 = unique(x$groupID), group2 = unique(x$groupID))[,
   .(group1, group2, intersectionLength = unlist(Map(function(u, v) 
   length(intersect(x$color[x$groupID == u], 
      x$color[x$groupID == v])), group1, group2)))]

這是在翻轉組的情況下刪除欺騙的另一種選擇:

ans <- x[x, on=.(color), allow.cartesian=TRUE][groupID!=i.groupID, 
    .(intersectionLength=uniqueN(color)), 
    .(g1=pmin(groupID, i.groupID), g2=pmax(groupID, i.groupID))]

輸出:

     g1 g2 intersectionLength
  1: AT AT                  6
  2: AT CZ                  3
  3: AT DO                  6
  4: AT EW                  5
  5: AT FT                  4
 ---                         
347: XL YL                  3
348: XL ZF                  6
349: YL YL                  5
350: YL ZF                  3
351: ZF ZF                  7

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM