gpt4 book ai didi

r - 使用 R 到 COUNT() 和 GROUP_CONCAT(DISTINCT x)

转载 作者:行者123 更新时间:2023-12-01 07:09:45 25 4
gpt4 key购买 nike

我正在用 R 分析我的网络服务器日志:

data = read.table("/path/to/log", sep=" ")

这些日志包括最终用户的 IP 地址和 USER_ID(登录后)。

我正在寻找比平时更活跃的用户,或者比平时使用更多 IP 地址的用户。

我目前可以让 R 按 USER_ID 对记录进行分组和计数:
counts <- ddply(data, .(data$user_id), nrow);
names(counts) <- c("user_id", "freq");
print(counts[order(counts$freq),c(2,1)], row.names = FALSE);

freq user_id
1 10171
40 7433
94 210
102 2043

但我还想添加 GROUP_CONCAT(DISTINCT IP) 的等效项,如 SQL 中所示,我也可以在其中看到该用户的不同 IP 地址的列表。
freq  user_id  ips
1 10171 192.168.0.1
40 7433 192.168.0.5,192.168.0.2
94 210 192.168.0.9
102 2043 192.168.0.1,192.168.0.3,192.168.0.8

在 SQL 中,它看起来像:
SELECT
user_id,
COUNT(id) AS freq,
GROUP_CONCAT(DISTINCT ip SEPARATOR ",") AS ips
FROM
log_table
GROUP BY
user_id
ORDER BY
freq ASC;

这可能通过aggregate() 函数实现,但我目前还没有弄清楚如何实现。

最佳答案

我们可以dplyr .我们按“user_id”分组,然后将“freq”作为行数(n())和“ips”作为paste(unique(ip), collapse=', ') (或者我们使用 toString 作为包装器)。

library(dplyr) 
data %>%
group_by(user_id) %>%
summarise(freq= n(), ips= toString(unique(ip)))
#not sure we wanted the nrow or `length` of `unique` 'ip'
#if the latter is the case
#summarise(freq=n_distinct(ip), ips = toString(unique(ip)))

如果我们想要一个 base R解决方案
do.call(data.frame, aggregate(ip~user_id, data,
FUN= function(x) c(freq= length(unique(ip)), ips=toString(unique(ip))))

关于r - 使用 R 到 COUNT() 和 GROUP_CONCAT(DISTINCT x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34268227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com