簡體   English   中英

R - 如何比較兩個數據幀的行並返回每種情況下相同值的計數

[英]R - how to compare rows of two data frames and return the count of identical values for each case

我是 R 的新手,需要您的幫助。 我有兩個數據框: dat1dat2

dat1 <- data.frame(X1 = c(9, 21, 30), X2 = c(3, 25, 47), X3 = c(13, 26, 51))
dat2 <- data.frame(X1 = c(3, 21, 30), X2 = c(7, 19, 47), X3 = c(13, 35, 51))

數據1

 X1 X2 X3
1  9  3 13
2 21 25 26
3 30 47 51

數據2

 X1 X2 X3
1  3  7 13
2 21 19 35
3 30 47 51

我想要的是將dat1的每一行中的值與所有dat2行中的值進行比較,並返回一個語句或每種情況下匹配值的數量。 像這樣的東西:

dat1 row 1 and dat2 row 1: 2 match
dat1 row 1 and dat2 row 2: 0 match
dat1 row 1 and dat2 row 3: 0 match
dat1 row 2 and dat2 row 1: 0 match
dat1 row 2 and dat2 row 2: 1 match
dat1 row 2 and dat2 row 3: 0 match
...

我希望你能理解我的想法。 聲明不必這么長。 我只想了解如何對兩個數據框進行此類比較。

謝謝!

如果你可以采用矩陣格式,那么

myfun <- Vectorize(function(a, b) sum(dat1[a,] %in% dat2[b,]), vectorize.args = c("a", "b"))
outer(seq_len(nrow(dat1)), seq_len(nrow(dat2)), myfun)
#      [,1] [,2] [,3]
# [1,]    2    0    0
# [2,]    0    1    0
# [3,]    0    0    3

如果您更喜歡垂直性質:

eg <- expand.grid(a = seq_len(nrow(dat1)), b = seq_len(nrow(dat2)))
eg$in_common <- with(eg, myfun(a, b))
eg
#   a b in_common
# 1 1 1         2
# 2 2 1         0
# 3 3 1         0
# 4 1 2         0
# 5 2 2         1
# 6 3 2         0
# 7 1 3         0
# 8 2 3         0
# 9 3 3         3

試試下面的代碼片段:

for(I  in 1:3){
  for(J in 1:3){
    print(sum(dat1[I,] %in% dat2[J,]))
  }
}

這是一個使用expand.gridapply的簡單方法,它計算dat1dat2行之間的匹配數,無論順序如何:

result <-
  apply(expand.grid(seq(1,nrow(dat1)),seq(1,nrow(dat2))), 1, 
        function(x){data.frame(dat1 = x[1], dat2 = x[2],
                    matches = (ncol(dat1) + ncol(dat2)) -
                      length(unique(c(dat1[x[1],],dat2[x[2],]))))
         })
result <- do.call(rbind,result)
result
#      dat1 dat2 matches
#Var1     1    1       2
#Var11    2    1       0
#Var12    3    1       0
#Var13    1    2       0
#Var14    2    2       1
#Var15    3    2       0
#Var16    1    3       0
#Var17    2    3       0
#Var18    3    3       3

暫無
暫無

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

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