Updated02(需要做一些小的调整)
我不得不问两个问题才能解决它。如果您经常处理此类问题,则需要学习igraph 包,该包主要用于网络分析。也许有一种更简单的方法,但现在我认为它会做。让我们带您了解一下:
library(dplyr)
library(purrr)
# In the firs chunk we iterate over every row of your data set to find out
# whether there is a connection between the corresponding rows and the others
map(1:nrow(dat), function(x) {
dat %>%
mutate(id = row_number()) %>%
pmap_lgl(., ~ {x <- unlist(dat[x,]);
any(x %in% c(...))})
}) %>%
exec(cbind, !!!.) %>%
as.data.frame() -> dat2
dat2 %>%
pmap(~ sub("V", "", names(dat2))[c(...)] %>% as.numeric()) -> ids
[[1]]
[1] 1 2
[[2]]
[1] 1 2 3
[[3]]
[1] 2 3 4
[[4]]
[1] 3 4 5
[[5]]
[1] 4 5 8
[[6]]
[1] 6
[[7]]
[1] 7
[[8]]
[1] 5 8
然后我们将所有相关的ids 组合在一起。这部分我使用了我亲爱的朋友@det 和@Ian Campbell 提出的solutions,因为我不知道如何使用igraph。
library(igraph)
map(ids, function(a) map_int(ids, ~length(base::intersect(a, .x)) > 0) * 1L) %>%
reduce(rbind) %>%
graph.adjacency() %>%
as.undirected() %>%
components() %>%
pluck("membership") %>%
split(seq_along(.), .) %>%
map(~unique(unlist(ids[.x]))) -> grouped_ids
$`1`
[1] 1 2 3 4 5 8
$`2`
[1] 6
$`3`
[1] 7
在我们将所有相关的数据组合在一起之后,我们就可以对我们的数据集进行分组:
dat %>%
mutate(id = row_number()) %>%
rowwise() %>%
mutate(grp = seq(length(grouped_ids))[map_lgl(grouped_ids, ~ id %in% .x)])
user_id phone_number id grp
1 101 4030201 1 1
2 102 4030201 2 1
3 102 4030202 3 1
4 103 4030202 4 1
5 103 4030203 5 1
6 106 4030204 6 2
7 107 4030205 7 3
8 111 4030203 8 1
数据
structure(list(user_id = c(101, 102, 102, 103, 103, 106, 107,
111), phone_number = c(4030201, 4030201, 4030202, 4030202, 4030203,
4030204, 4030205, 4030203)), class = "data.frame", row.names = c(NA,
-8L))