[英]sorting data frame and calculating instant value of a column
我有一個相對較大的數據框(150 萬行和 5 列)。 為簡單起見,我在下面創建了一個示例數據框:
date <- c("2018-07-06","2017-04-13","2017-09-12","2018-09-19"
,"2019-03-04","2017-05-21","2018-05-15")
data <- as.Date(date)
TV_ad<-c(0,1,0,0,1,0,1)
ID <- c(1315769,1300620,1300620,1315769,1300620,1315769,1300620)
result <- data.frame(ID,TV_ad,date)
ID TV_ad date
1 1315769 0 2018-07-06
2 1300620 1 2017-04-13
3 1300620 0 2017-09-12
4 1315769 0 2018-09-19
5 1300620 1 2019-03-04
6 1315769 0 2017-05-21
7 1300620 1 2018-05-15
我想做什么,對於每個特定的 ID,在特定的時間,我想計算該人在之前所有日期使用 TV_ad 的次數比率。 我能想象到的最簡單的方法是先選擇一個特定的 ID,然后根據日期對小數據框進行排序並計算每個日期的 TV_ad 比率。 例如,對於ID=1300620,首先我構建了一個按日期排序的小數據框,如下所示:
ID TV_ad date
2 1300620 1 2017-04-13
3 1300620 0 2017-09-12
7 1300620 1 2018-05-15
5 1300620 1 2019-03-04
然后我可以計算每一行的比率。 對於第一行,第二行是 1/1=1,第三行是 1/2=0.5 2/3=0.66,第四行是 3/4=0.75
我得到這個結果:
ID TV_ad date ratio
1 1315769 0 2018-07-06 0.00
2 1300620 1 2017-04-13 1.00
3 1300620 0 2017-09-12 0.50
4 1315769 0 2018-09-19 0.00
5 1300620 1 2019-03-04 0.75
6 1315769 0 2017-05-21 0.00
7 1300620 1 2018-05-15 0.66
但是,這種方法在我的大型數據集上會很耗時。 有什么建議可以更快地進行此計算嗎?
您不需要拆分數據,您可以使用dplyr
在 1 個 data.frame 上完成所有dplyr
:
library(dplyr)
result %>%
arrange(ID, date) %>%
group_by(ID) %>%
mutate(ratio = cumsum(TV_ad) / seq_len(n()))
給出:
ID TV_ad date ratio
<dbl> <dbl> <fct> <dbl>
1 1300620 1 2017-04-13 1
2 1300620 0 2017-09-12 0.5
3 1300620 1 2018-05-15 0.667
4 1300620 1 2019-03-04 0.75
5 1315769 0 2017-05-21 0
6 1315769 0 2018-07-06 0
7 1315769 0 2018-09-19 0
或者你可以使用data.table
:
library(data.table)
setDT(result)
result <- result[order(ID, date)]
result[, ratio := cumsum(TV_ad) / seq_len(.N), by = ID]
(您不需要按ID
訂購它純粹是為了輸出文本可見性)
> result_ord <- result[order(result$ID, result$date), ]
> result_ord$cumAvg_by_ID <- ave(result_ord$TV_ad, list(result_ord$ID), FUN=function(x) cumsum(x) / 1:length(x) )
輸出:
> result_ord
ID TV_ad date cumAvg_by_ID
2 1300620 1 2017-04-13 1.0000000
3 1300620 0 2017-09-12 0.5000000
7 1300620 1 2018-05-15 0.6666667
5 1300620 1 2019-03-04 0.7500000
6 1315769 0 2017-05-21 0.0000000
1 1315769 0 2018-07-06 0.0000000
4 1315769 0 2018-09-19 0.0000000
>
(正如上面@det 所指出的,只有按date
排序是絕對必要的)。
參考: https : //stat.ethz.ch/pipermail/r-help/2010-October/255987.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.