2014-05-22 2 views
0

저는 this question에서와 동일하게하고 싶지만, 이번에는 음 이항 분포를 플롯에 더합니다.scatterplot에 음 이항 분포를 덧붙입니다.

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, 크기 및 확률값이 필요합니다

이 내 코드입니다. 누구든지 줄거리에 음 이항 분포를 추가하는 방법을 알고 있습니까?

답변

2

나는 MASS에서 rnegbin을 사용할 것입니다.

여기에는 시뮬레이션 된 포인트의 수인 n이 사용됩니다. 모델의 예측값

MU 및 모델로부터 예상 세타 같은

세타.

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) 

enter image description here

관련 문제