Re: [問題] 計算累積機率

作者: celestialgod (天)   2015-11-16 09:14:46
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
: 請問在資料量很大的情況下
: 有沒有推薦較有效率的方法
作者: Udyr (Udyr)   2015-11-18 13:20:00
謝謝!

Links booklink

Contact Us: admin [ a t ] ucptt.com