我有一个巨大的数据集(〜7 Gb),我需要用相对频率(即freq(user_id)/ unique(user_id))有效地替换一个变量(iser ID)。最小示例:
id <- c(1050, 1324, 5, 7, 1050, 7, 8)
table(id)
id
5 7 8 1050 1324
1 2 1 2 1
然后我尝试
freq <- ave(id, id, FUN = function(X) length(X) / length(unique(id)))
df <- data.frame(id = id, freq = freq)
输出:
id freq
1 1050 0.4
2 1324 0.2
3 5 0.2
4 7 0.4
5 1050 0.4
6 7 0.4
7 8 0.2
但是根据我的数据集,该解决方案已经运行了三个小时!任何帮助表示赞赏:)
这是一个整洁的实现:
library(tidyverse)
id <- c(1050, 1324, 5, 7, 1050, 7, 8)
data_frame( id = id)-> my_df # creating df
my_df%>%
mutate(unique = unique(id) %>% length) %>% # addying column unique, with the number of unique id
group_by(id) %>% # group by id
mutate(
n=n(), # number of observations for the current group
freq = n / unique # n / unique gives the freq
)
如果您想了解有关group_by的更多信息,请查看此教程:https : //www.youtube.com/watch?v= 70UcgabaB_I&t = 14s
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句