作者celestialgod (天)
看板R_Language
标题Re: [问题] 计算累积机率
时间Mon Nov 16 09:14:46 2015
library(dplyr)
library(magrittr)
## data generation
numUsers = 1e5
numLevels = 5
userLevels = numUsers %>% replicate(1:sample(1:numLevels, 1),
simplify = FALSE)
df = lapply(1:numUsers, function(i) cbind(i, userLevels[[i]])) %>%
do.call(rbind, .) %>% data.frame %>% tbl_df %>%
set_names(c("user", "level"))
# The number of rows of df is 299,541 in my case
## solution
st = proc.time()
maxUserID = max(df$user)
out = df %>% group_by(level) %>%
summarise(cum.prob = sum(user %in% 1:maxUserID) / maxUserID)
# Source: local data frame [5 x 2]
#
# level cum.prob
# 1 1 1.00000
# 2 2 0.80032
# 3 3 0.59995
# 4 4 0.39829
# 5 5 0.19685
proc.time() - st
# user system elapsed
# 0.38 0.00 0.38
user不是数字没有编号的话,建议改成这样:
uniUserID = unique(df$user)
out = df %>% group_by(level) %>%
summarise(cum.prob = sum(user %in% uniUserID) / length(uniUserID))
※ 引述《Udyr (Udyr)》之铭言:
: [问题类型]:
: 程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
: [软体熟悉度]:
: 新手(没写过程式,R 是我的第一次)
: [问题叙述]:
: 资料的格式如下
: user level
: 1 1
: 1 2
: 1 3
: 1 4
: 1 5
: 2 1
: 2 2
: 2 3
: 3 1
: 3 2
: 3 3
: 3 4
: 4 1
: 4 2
: 5 1
: 5 2
: 5 3
: 5 4
: 5 5
: 其中level的最大值为5
: 想对level计算累积机率(有多少比例的user达到某一个特定的level)
: 以上面的资料 想得到的结果为
: level 5 4 3 2 1
: cum.prob 0.4 0.6 0.8 1 1
: 请问在资料量很大的情况下
: 有没有推荐较有效率的方法
--
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.109.73.89
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1447636490.A.BCB.html
※ 编辑: celestialgod (140.109.73.89), 11/16/2015 09:17:43
※ 编辑: celestialgod (140.109.73.89), 11/16/2015 09:25:39
1F:推 Udyr: 谢谢! 11/18 13:20