在不忽略其他变量的情况下获取某些变量的 data.frame 的交集

Get intersection in data.frame of some variables without omitting others

我有一个巨大的数据框(1500 万行),例如

    data = data.frame(
       human = c(1,0,0,1,1,0,0,0,0,1,1),
       hair = c(3,1,5,3,1,1,3,4,4,5,5),
       eye_colour = c(1,4,2,1,4,3,1,3,3,3),
       fuel = c(1,2,3,3,4,7,5,6,1,4,6)
    )

我想找到 human 的交集是 haireye_colour 的 0 和 1(所以只有当 haireye_colour 是至少 human==0human==1 相同,我想保留该行)并用 cyclon_individual 标记。因此,对于我的应用程序,cyclon_individual 是某人,他至少曾被记录为 human==1human==0 并且具有相同的 haireye_colour 编码,即以下内容结果:

    cyclon_individual human hair eye_colour fuel
    1                 1     3    1          1
    1                 1     3    1          3
    1                 0     3    1          5
    2                 0     1    4          2
    2                 1     1    4          4

我想,我采取了一种尴尬的方式,但我还没有找到一种巧妙的方法来将 cyclon_individual 编码为 dplyr:

    require('dplyr')
    hum = subset(data, human == 1)
    non_hum = subset(data, human == 0)
    feature_intersection = c("hair", "eye_colour")

    cyclon = intersect(hum[,feature_intersection],non_hum[,feature_intersection])
    cyclon_data = cyclon %>%
                    rowwise() %>%
                    do(filter(data,hair==.$hair,eye_colour==.$eye_colour))

那么有没有更直接的方式到达 cyclon_data,因为当前编码至少需要 26 小时? 是否有一种聪明的方法可以通过遍历 cyclon 的所有行来包含变量 cyclon_individual 而无需使用循环?

您可以简单地按头发和 eye_color 分组,并保留人类同时具有 0 和 1 的那些,即

library(dplyr)

data %>% 
 group_by(hair, eye_colour) %>% 
 filter(length(unique(human)) > 1)

这给出了,

# A tibble: 5 x 4
# Groups:   hair, eye_colour [2]
  human  hair eye_colour  fuel
  <dbl> <dbl>      <dbl> <dbl>
1     1     3          1     1
2     0     1          4     2
3     1     3          1     3
4     1     1          4     4
5     0     3          1     5 

我们可以使用 n_distinct 来自 dplyr

library(dplyr)
data %>%
  group_by(hair, eye_color) %>%
  filter(n_distinct(human) > 1)