更改信息时查找唯一用户 [英] Finding Unique Users When Changing Info
本文介绍了更改信息时查找唯一用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据:
dat <- data.frame(user_id = c(101,102,102,103,103,106),
phone_number = c(4030201, 4030201, 4030202, 4030202, 4030203, 4030204))
我要计算唯一用户。如您所见,这里有两个唯一的用户。因此,我最终想要创建的表如下:
user_id phone_number new_user_id
101 4030201 1
102 4030201 1
102 4030202 1
103 4030202 1
103 4030203 1
106 4030204 2
有什么想法可以用R来计算吗?或者使用不同的语言,然后我可以将代码翻译成R。
推荐答案
更新02(需要进行一些细微的调整)
我必须问两个问题才能解决这个问题。如果您经常处理这类问题,则需要学习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
然后我们将所有相关的id
分组在一起。对于这一部分,我使用了我亲爱的朋友@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))
这篇关于更改信息时查找唯一用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文