位數我想通過數據分離成位數,相同this great question怎樣計算在團體
的問題是,我要天天在時間序列上做到這一點:
set.seed(123)
temp.all <- data.frame(date = c(rep(Sys.Date() - 1, 12), rep(Sys.Date(), 12)),
name=letters[c(1:12, 1:12)], value=rnorm(24))
在此刻,我正在用for循環解決:
library(dplyr)
for (d in unique(temp.all$date)) {
temp = filter(temp.all, date == d)
temp$quartile <- with(temp, factor(
findInterval(val, c(-Inf,
quantile(val, probs=c(0.25, .5, .75)), Inf) , na.rm=TRUE),
labels=c("Q1","Q2","Q3","Q4")
))
# ...and doing rbind on 'temp' to reconstruct temp.all with quartiles
}
有關如何避免可怕的for-loop的任何想法?有沒有這樣做的group_by
方式?
'ntile'函數可以任意打斷關係,所以我會堅持'cut'。我明白你的觀點:使用'group_by'然後'mutate'。謝謝! – lebelinoz
我同意@Uwe,代碼適用於示例數據,但會在一個多月的同一天給出錯誤答案。只是'group_by(date)'應該這樣做。 – neilfws