I have a dataset in which participants went through 5 different situations and their behavior was measured in each situation. Here's an example dataset with a similar structure:
id1<-1:10
id<-rep(id1, each=5)
socbeh<-as.integer(rnorm(50, 3, 1))
Index1<-1:5
situation<-rep(Index1, times=10)
df<-data.frame(id, situation, socbeh)
I'm running multilevel regressions using R lme4 with participant ID as a random effect and situation as 5-level factorial predictor, like this:
library(lme4)
model<-lmer(socbeh ~ (1|id)+factor(situation), data=df)
#and then derive the estimated marginal means via emmeans
library(emmeans)
em<-emmeans(model, ~situation)
I'd like to conduct nonparametric bootstrap on the estimated marginal means and on their confidence intervals. However, all my attempts produce the error:
Error in t.star[r, ] <- res[[r]] :
number of items to replace is not a multiple of replacement length
I first tried the following:
fun<-function(data, idx){
model<-lmer(socbeh ~ (1|id) + factor(situation),
data=data[idx,])
rg<-ref_grid(model, mult.levs = rm_levels)
em_<-emmeans(rg, ~situation)
}
B<-boot(df, fun, R=1000)
However, this produces the error: "Error in t.star[r, ] <- res[[r]] : number of items to replace is not a multiple of replacement length"
I tried removing all NAs from the data -> same error.
I tried perusing the advice in this response: :
df2 <- model.matrix(~socbeh + situation + id - 1, data=df)
and then ran the boot again using df2 as the data, but I still get the same error.
I also tried a simpler version of the function:
fun<-function(data, idx){
model<-lmer(socbeh ~ (1|id) + factor(situation),
data=data[idx,])
em<-emmeans(model, ~situation)
}
But got the same error again. I also tried to bootstrap just the regression coefficients by
fun<-function(data, idx) {
coef(lmer(socbeh ~ (1|id)+factor(situation), data=data[idx,]))
}
B<-boot(df2, fun, R=1000)
which has worked for me before (with continuous predictors), but now I get this error "Error in model.frame.default(data = data[idx, ], drop.unused.levels = TRUE, : variable lengths differ (found for 'factor(situation)')"
It probably goes without saying I'm very inexperienced in programming, and don't understand at all what's going on. Can anyone help? Thanks so much in advance!