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

看板R_Language作者 (天)時間8年前 (2015/11/16 09:14), 8年前編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
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://www.ptt.cc/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

11/18 13:20, , 1F
謝謝!
11/18 13:20, 1F
文章代碼(AID): #1MIIuAlB (R_Language)
討論串 (同標題文章)
文章代碼(AID): #1MIIuAlB (R_Language)