我希望做与此问题相同的操作,但是这次向该图添加了一个负二项式分布。
这是我的代码:
library(ggplot2); library(MASS)
year <- 1990:2009
set.seed(1)
counts <- sample(1:1000, 20)
df <- data.frame(year, counts)
my_nb_reg <- glm.nb(counts ~ year, data = df)
my_nb_reg$model$fitted <- predict(my_nb_reg, type = "response")
library(plyr)
# nb_sim <- unlist(llply(my_nb_reg$model$fitted, function(x) rnbinom(n = ?, size = ?, prob = ?, mu = x)))
df.new <- data.frame(year, nb_sim)
ggplot(my_nb_reg$model) + geom_point(aes(year, counts)) + geom_jitter(data= nb_sim, aes(year, nb_sim), color = "red")
注释掉的行需要参数n,大小和概率。有人知道如何将负二项式分布添加到情节吗?
我会rnegbin
从MASS使用。
这是使用:n作为模拟点的数量。
mu作为模型的预测值,
theta作为模型的估计theta。
library(ggplot2); library(MASS)
year <- 1990:2009
set.seed(1)
counts <- sample(1:1000, 20)
df <- data.frame(year, counts)
my_nb_reg <- glm.nb(counts ~ year, data = df)
my_nb_reg$model$fitted <- predict(my_nb_reg, type = "response")
nb_sim <- unlist(lapply(my_nb_reg$model$fitted, function(x) rnegbin(n = 1000, mu = x, theta = my_nb_reg$theta)))
df.new <- data.frame(year, nb_sim)
ggplot() +
geom_jitter(data = df.new, aes(year, nb_sim), color = "red", alpha = 0.2) +
geom_point(data = my_nb_reg$model, aes(year, counts)) +
geom_point(data = my_nb_reg$model, aes(year, fitted), shape = 'x', size = 4)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句