dplyr解决方案
library(dplyr)
首先我们合并数据:
使用rbind() 并引入一个名为ref 的新变量以了解每个观察的来源:
both <- rbind( f1, f2 )
both$ref <- rep( c( "f1", "f2" ) , c( nrow(f1), nrow(f2) ) )
然后计算观察结果:
创建另一个新变量,其中包含每个 ref 和 x 组合的观察次数:
both_with_counts <- both %>%
group_by( ref ,x ) %>%
mutate( counts = n() )
然后过滤最大计数:
both_with_counts %>% group_by( x ) %>% filter( n==max(n) )
注意:您也可以只选择 x 和 y 列和 select(x,y)...
这给出了:
## Source: local data frame [7 x 4]
## Groups: x
##
## x y ref counts
## 1 a 1 f1 2
## 2 a 1 f1 2
## 3 c 3 f1 3
## 4 c 3 f1 3
## 5 c 3 f1 3
## 6 b 5 f2 2
## 7 b 5 f2 2
现在……
what_I_want <-
rbind(cbind(f1,ref = "f1"),cbind(f2,ref = "f2")) %>%
group_by(ref,x) %>%
mutate(counts = n()) %>%
group_by( x ) %>%
filter( counts==max(counts) ) %>%
select( x, y )
因此:
> what_I_want
# Source: local data frame [7 x 2]
# Groups: x
#
# x y
# 1 a 1
# 2 a 1
# 3 c 3
# 4 c 3
# 5 c 3
# 6 b 5
# 7 b 5