子集数据基于R中的另一个数据

时间:2015-12-04 12:53:08

标签: r dataframe subset

我有两个数据集dat1dat2,如下所示:

a<-c(rep(1,5), rep(2,3), rep(1,2), rep(2,4), rep(1,2))
b<-c(rep("AA", 8), rep("BB", 6), rep("CC", 2))
v<-c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", 
"x4", "x5", "x6", "x7", "x8", "x9", "x5", "x8")
ab<-c(1,2,5,6,58,2,4,14,2,25,23,1,12,14,15,14)
dat1<-data.frame(a,b,v,ab)
names(dat1)<-c("loc", "point", "sp", "ab")

a<-c(rep(1,8), rep(2,4), rep(3, 2), rep(1,4))
b<-c(rep("AA", 8), rep("BB", 6), rep("DD", 4))
v<-c("y1", "y2", "y3", "y4", "y6", "y7", "y8", "y12",
"y1", "y2", "y3", "y4", "y5", "y6", "y1", "y2", "y3", "y6")
ab<-c(1,2,45,14,1,12,14,15,10,2,32,14,1,12,18,9,6,7)
dat2<-data.frame(a,b,v,ab)
names(dat2)<-c("loc", "point", "sp", "ab")

我需要制作这些数据框的子集,其中每个子集仅包含locpoint中的dat1dat2的组合。 我的结果应该是这样的:

res1
   loc point sp ab
1    1    AA x1  1
2    1    AA x2  2
3    1    AA x3  5
4    1    AA x4  6
5    1    AA x5 58
11   2    BB x6 23
12   2    BB x7  1
13   2    BB x8 12
14   2    BB x9 14

res2
   loc point  sp ab
1    1    AA  y1  1
2    1    AA  y2  2
3    1    AA  y3 45
4    1    AA  y4 14
5    1    AA  y6  1
6    1    AA  y7 12
7    1    AA  y8 14
8    1    AA y12 15
9    2    BB  y1 10
10   2    BB  y2  2
11   2    BB  y3 32
12   2    BB  y4 14

我已尝试过merge()并将结果除以两个数据帧,但行数不同,因此较小数据的行数会相乘以填补空白。我对subset()的尝试也失败了。

这与Subset a data frame based on another类似,但即使在我解决他们的解决方案(即intersect)时我也没有成功。

寻求帮助!

2 个答案:

答案 0 :(得分:2)

恕我直言,你可以尝试:

merge(dat1, unique(dat2[,1:2]))
merge(dat2, unique(dat1[,1:2]))

答案 1 :(得分:1)

dplyr 包中的

semi_join专为此设计:

library(dplyr)
# get just the rows in dat1 that have matches in dat2
dat1 %>% semi_join(dat2, by=c('loc', 'point'))