I have this data set:
library(data.table)
my_data <- data.table(group=rep(c("a", "b"), each=50),
x=c(11:60, 11:60),
y=c(exp(0.1)*(11:60)+rnorm(50),
exp(0.3)* (11:60)^3)+rnorm(50))
and I fit this non-linear mixed effect model
library(lme4)
start <- c(b1=0.2, b2=2)
nform <- ~ exp(b1)*(input^b2)
nfun <- deriv(nform, namevec=c("b1", "b2"),
function.arg=c("input","b1", "b2"))
nlmer_model <- nlmer(y~ nfun(x, b1, b2)~(b1|group)+(b2|group),
data=my_data, start = start)
Next, I want to predict y on a new data set. For simplicity:
new_data <- my_data[, .(group, x)]
One way to do it is to get the fixed and random effects:
fixed_effects <- fixef(nlmer_model)
random_effects <- ranef(nlmer_model)$group
b1 <- fixed_effects[1] + random_effects$b1
b2 <- fixed_effects[2] + random_effects$b2
coeff <- data.table(grp=row.names(random_effects), b1, b2)
new_data2 <- merge(new_data, coeff, by="grp")
new_data2[, y := exp(b1)*(x^b2)]
I thought I could get the same results using predict(), but I couldn't make it work. Both
pred <- predict(nlmer_model, new_data)
pred <- predict(nlmer_model, new_data, re.form=~(b1|group)+(b2|group))
get the message:
"Error in model.frame.default(tt, newdata.NA, na.action = na.pass,
xlev = orig.random.levs) : variable lengths differ (found for 'group')"
How can I get the same results as in new_data2, using predict()?