I had a model of the form mod = lmer(y ~ A + B + (1|line))
y
is the continuous response variable, about 2000 rowsA
andB
are fixed effects with 2 levels (non present / present)line
is a random effect with about 100 levels
In order to predict the response variable, all I had to do is construct a New_Data
data frame (100 x 3) with the first column having all lines, and 2 and 3 zeros
Then I hit adjusted = predict(mod, New_Data)
. Worked fine.
Now due to a different experimental design, I have an additional random effect, that line is nested within. The model becomes:
mod = lmer(y ~ A + B + (1|batch) + (1|batch:line))
again I constructed a New_Data
data frame, now having 4 columns, column 4 having batch at level 1 (out of 4 possible levels)
but now when trying to predict, the predict function tells me:
Error in levelfun(r, n, allow.new.levels = allow.new.levels) : new levels detected in newdata
What am I doing wrong?
Minimal Example
library(lme4)
library(data.table)
lines <- factor(c('line.c', 'line.c', 'line.b', 'line.b', 'line.a', 'line.a',
'line.d', 'line.d', 'line.e', 'line.e'))
Model_Data <- data.table(y = rnorm(10),
A = factor(c('a', 'a', 'b', 'b', 'b', 'a', 'a', 'c', 'c', 'c')),
B = lines,
C = factor(c(rep(1, 4), rep(2, 4), 3, 3)))
My_Model <- Model_Data[, lmer(y ~ A + (1|C) + (1|C:B))]
Prediction_Data <- data.table(B = levels(lines),
A = factor('a', levels=c('a', 'b', 'c')),
C = factor(1, levels=c(1,2,3)))
y.adjusted <- predict(My_Model, Prediction_Data)