我有一个负二项回归模型,我根据他们对某些单词类型(ME单词,道德单词和情感单词)的使用来预测Twitter短信的转发计数:
M1 <- glm.nb(retweetCount ~ ME_words + Moral_words + Emo_words, data = Tweets)
我现在想要从大数据集Tweets
中进行自举(例如,从数据帧的原始500,000条消息中替换的1,000个样本)进行采样,以运行模型的迭代并分析系数的方差。这样做的最佳方法是什么?我假设我需要使用boot
包,但我有点迷失在哪里开始。
理想情况下,我想创建一个可以运行多次迭代的for循环,然后将每个模型迭代的系数存储在一个新的数据帧中。这对未来的分析非常有用。
以下是来自大量数据框Tweets
的一些可重现数据:
>dput((head(Tweets, 100)))
structure(list(retweetCount = c(1388, 762, 748, 436, 342, 320,
312, 295, 264, 251, 196, 190, 175, 167, 165, 163, 149, 148, 148,
146, 133, 132, 126, 124, 122, 122, 121, 120, 118, 118, 114, 113,
112, 110, 108, 107, 104, 101, 100, 96, 95, 94, 93, 92, 90, 90,
89, 89, 87, 86, 84, 83, 83, 83, 82, 82, 82, 82, 78, 78, 78, 76,
76, 76, 76, 74, 74, 73, 73, 72, 72, 71, 70, 70, 70, 70, 69, 69,
69, 68, 68, 67, 65, 65, 65, 65, 63, 62, 62, 61, 61, 61, 61, 60,
60, 59, 59, 59, 59, 58), ME_words = c(2, 2, 2, 0, 0, 1, 1, 0,
1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1,
0, 3, 0, 1, 0, 1, 1, 4, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0,
0, 0, 2, 2, 0, 0, 1, 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 1, 1, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 1, 0, 0), Moral_words = c(0, 0, 1, 1, 1, 2, 0,
0, 0, 1, 0, 1, 2, 0, 1, 1, 1, 2, 0, 1, 0, 1, 1, 0, 2, 0, 1, 1,
1, 0, 1, 1, 1, 1, 0, 2, 0, 1, 1, 1, 2, 0, 1, 1, 1, 1, 0, 1, 0,
0, 5, 1, 1, 1, 1, 2, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 2, 0, 0, 0,
1, 1, 2, 0, 0, 0, 0, 0, 1, 3, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1,
1, 1, 0, 0, 2, 2, 1, 0, 0), Emo_words = c(0, 0, 1, 1, 0, 0, 2,
0, 1, 0, 2, 0, 1, 0, 1, 2, 0, 3, 1, 1, 2, 0, 0, 0, 0, 0, 1, 1,
1, 2, 0, 1, 0, 0, 0, 1, 0, 1, 0, 2, 0, 0, 1, 0, 1, 1, 2, 0, 0,
1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 3, 0, 0, 2, 0, 0, 1, 0,
1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 2, 2, 1, 0, 0, 0, 0, 2, 1, 0, 0,
1, 0, 0, 1, 2, 2, 0, 0, 0)), row.names = c(NA, -100L), class = c("tbl_df",
"tbl", "data.frame"))
您可以使用boot
软件包,但对于简单版本的引导程序来说,滚动自己的软件几乎更简单。
library(MASS)
M1 <- glm.nb(retweetCount ~ ME_words + Moral_words +
Emo_words, data = Tweets)
nboot <- 1000
bres <- matrix(NA,nrow=nboot,
ncol=length(coef(M1)),
dimnames=list(rep=seq(nboot),
coef=names(coef(M1))))
set.seed(101)
bootsize <- 200
for (i in seq(nboot)) {
bdat <- Tweets[sample(nrow(Tweets),size=bootsize,replace=TRUE),]
bfit <- update(M1, data=bdat) ## refit with new data
bres[i,] <- coef(bfit)
}
data.frame(mean_est=colMeans(bres),
t(apply(bres,2,quantile,c(0.025,0.975))))