[英]Compare item in one row against all other rows and loop through all rows using data.table - R
[英]Compare one row to all other rows in a file using R
我有一個如下文件:
P1 A,B,C
P2 B,C,D,F
P3 C,D,E,F
我需要將每一行與所有其他行進行比較,以得到相交元素的數量,如下所示:
P1 P2 2
P1 P3 1
P2 P3 3
謝謝,
小號
目前尚不清楚原始數據來自何處,因此我假設您將數據讀入data.frame中,如下所示:
x <- data.frame(V1 = c("a", "b", "c"),
V2 = c("b", "c", "d"),
V3 = c("c", "d", "e"),
V4 = c(NA, "f", "f"),
stringsAsFactors = FALSE
)
row.names(x) <- c("p1", "p2", "p3")
第一步是創建需要比較的所有行的組合:
rowIndices <- t(combn(nrow(x), 2))
> rowIndices
[,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 2 3
然后,在我們可以利用這些信息apply
與length()
和intersect()
得到你想要的東西。 注意,我還索引了data.frame x
的row.names()
屬性,以獲取所需的行名。
data.frame(row1 = row.names(x)[rowIndices[, 1]],
row2 = row.names(x)[rowIndices[, 2]],
overlap = apply(rowIndices, 1, function(y) length(intersect(x[y[1] ,], x[y[2] ,])))
)
給您類似的東西:
row1 row2 overlap
1 p1 p2 2
2 p1 p3 1
3 p2 p3 3
讀取示例數據。
txt <- "P1 A,B,C
P2 B,C,D,F
P3 C,D,E,F"
tc <- textConnection(txt)
dat <- read.table(tc,as.is=TRUE)
close(tc)
轉換為長格式,並使用具有聚合功能的自連接。
dat_split <- strsplit(dat$V2,",")
dat_long <- do.call(rbind,lapply(seq_along(dat_split),
function(x) data.frame(id=x,x=dat_split[[x]], stringsAsFactors=FALSE)))
result <- sqldf("SELECT t1.id AS id1,t2.id AS id2,count(t1.x) AS N
FROM dat_long AS t1 INNER JOIN dat_long AS t2
WHERE (t2.id>t1.id) AND (t1.x=t2.x) GROUP BY t1.id,t2.id")
結果
> result
id1 id2 N
1 1 2 2
2 1 3 1
3 2 3 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.