我有一个巨大的数据集(~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
但在我的数据集上,该解决方案已经工作了三个(!)小时。如有任何帮助,我们将不胜感激:)
最佳答案
这是一个 tidyverse 实现:
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
关于r - 用R中的相对频率有效替换数据框列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57953635/