這是this question的稍後續。我想使用dplyr
函數而不是ddply
來應用一個函數,該函數會生成幾個直接包含在結果中的行。我想這是在下面的例子中最好的解釋:ddply - > dplyr:.fun =總結了幾行
library(plyr)
#library(dplyr)
dfx <- data.frame(
group = c(rep('A', 8), rep('B', 15), rep('C', 6)),
sex = sample(c("M", "F"), size = 29, replace = TRUE),
age = runif(n = 29, min = 18, max = 54)
)
p <- c(.2,.4,.6,.8)
ddply(dfx, .(group), .fun = summarize, p=p, stats=quantile(age,probs=p))
# dfx %>% group_by(group) %>% do(p=p, stats=quantile(.$age, probs=p))
的ddply的解決方案看起來像這樣(不加載dplyr
這個工作):
# group p stats
# 1 A 0.2 32.81104
# 2 A 0.4 34.13195
# 3 A 0.6 37.34055
# 4 A 0.8 44.21874
# 5 B 0.2 25.58858
# 6 B 0.4 34.67511
# 7 B 0.6 40.68370
# 8 B 0.8 44.67346
# 9 C 0.2 37.22625
# 10 C 0.4 42.46769
# 11 C 0.6 43.27065
# 12 C 0.8 44.54724
的dplyr
溶液(註釋行)產生以下結果:
# group p stats
# 1 A <dbl[4]> <dbl[4]>
# 2 B <dbl[4]> <dbl[4]>
# 3 C <dbl[4]> <dbl[4]>
這裏,數據在列表元素中是「隱藏」的。有沒有辦法直接得到上面的ddply
解決方案? (請注意,我張貼這個問題上manipulatr mailing list,至今沒有答案)
感謝您的解釋和鏈接,它幫助我瞭解@akrun的解決方案。 – sebschub
哈德利斯博客的鏈接提供了迄今爲止我所見過的最有用的解釋。非常感謝你! – User632716