【发布时间】:2018-01-21 02:19:14
【问题描述】:
我的问题以粗体结尾。
我知道如何将 beta 分布拟合到某些数据。例如:
library(Lahman)
library(dplyr)
# clean up the data and calculate batting averages by playerID
batting_by_decade <- Batting %>%
filter(AB > 0) %>%
group_by(playerID, Decade = round(yearID - 5, -1)) %>%
summarize(H = sum(H), AB = sum(AB)) %>%
ungroup() %>%
filter(AB > 500) %>%
mutate(average = H / AB)
# fit the beta distribution
library(MASS)
m <- MASS::fitdistr(batting_by_decade$average, dbeta,
start = list(shape1 = 1, shape2 = 10))
alpha0 <- m$estimate[1]
beta0 <- m$estimate[2]
# plot the histogram of data and the beta distribution
ggplot(career_filtered) +
geom_histogram(aes(average, y = ..density..), binwidth = .005) +
stat_function(fun = function(x) dbeta(x, alpha0, beta0), color = "red",
size = 1) +
xlab("Batting average")
产生:
现在我想为数据的每个 batting_by_decade$Decade 列计算不同的 beta 参数 alpha0 和 beta0,所以我最终得到 15 个参数集和 15 个 beta 分布,我可以拟合这个击球平均值的 ggplot由十年分面:
batting_by_decade %>%
ggplot() +
geom_histogram(aes(x=average)) +
facet_wrap(~ Decade)
我可以通过过滤每个十年来硬编码,并将该十年的数据传递给fidistr 函数,在所有十年中重复此操作,但是有没有一种方法可以快速计算每十年的所有 beta 参数并且可重现,也许使用其中一种应用功能?
【问题讨论】:
标签: r ggplot2 dplyr apply beta-distribution