通过R中的条件匹配数据集

时间:2018-08-05 10:48:10

标签: r dataframe dplyr data.table

有数据集

data=structure(list(x1 = structure(c(1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L), .Label = c("q", 
"r", "w"), class = "factor"), x2 = structure(c(2L, 2L, 2L, 2L, 
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
), .Label = c("e", "w"), class = "factor"), x3 = structure(c(1L, 
1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 
2L, 2L, 2L), .Label = c("e", "q", "r"), class = "factor"), var = c(34L, 
35L, 34L, 34L, 34L, 34L, 35L, 34L, 34L, 34L, 34L, 35L, 34L, 34L, 
34L, 34L, 34L, 34L, 34L, 34L), act = c(1L, 1L, 1L, 1L, 1L, 0L, 
0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), .Names = c("x1", 
"x2", "x3", "var", "act"), class = "data.frame", row.names = c(NA, 
-20L))

根据x1,x2,x3列,我们有三组

q   w   e
w   e   r
r   e   q

有另一个数据集。它构成

dat= structure(list(x1 = structure(1:2, .Label = c("q", "r", "w"), class = "factor"), 
     x2 = structure(c(2L, 1L), .Label = c("e", "w"), class = "factor"), 
     x3 = structure(1:2, .Label = c("e", "q", "r"), class = "factor")), 
     class = "data.frame", row.names = c(NA,-2L), .Names = c("x1", "x2", "x3"))

IE。

  x1 x2 x3
1  q  w  e
2  r  e  q

如何比较数据集datadat,在数据集data中仅观察数据集dat中指示的组

I.E。输出

x1  x2  x3  var act
q   w   e   34  1
q   w   e   35  1
q   w   e   34  1
q   w   e   34  1
q   w   e   34  1
r   e   q   34  1
r   e   q   34  1
r   e   q   34  1
r   e   q   34  1
r   e   q   34  1

注意:这是测试数据。团体很多。

1 个答案:

答案 0 :(得分:1)

由于您希望将两个数据框以相同的列名称进行连接,因此我们可以做到

library(dplyr)
inner_join(data, dat)

Joining, by = c("x1", "x2", "x3")
   x1 x2 x3 var act
1   q  w  e  34   1
2   q  w  e  35   1
3   q  w  e  34   1
4   q  w  e  34   1
5   q  w  e  34   1
6   r  e  q  34   1
7   r  e  q  34   1
8   r  e  q  34   1
9   r  e  q  34   1
10  r  e  q  34   1