I have two models - one is including a categorical covariate as a fixed effect, the other includes it as a random effect:
require(nlme)
set.seed(123)
n <- 100
k <- 5
cat <- as.factor(rep(1:k, n))
cat_i <- 1:k # intercept per kategorie
x <- rep(1:n, each = k)
sigma <- 0.2
alpha <- 0.001
y <- cat_i[cat] + alpha * x + rnorm(n*k, 0, sigma)
plot(x, y)
m2 <- lm(y ~ cat + x)
summary(m2)
m3 <- lme(y ~ x, random = ~ 1|cat, na.action = na.omit)
summary(m3)
As you can see, both models m2
and m3
produce exactly the same coefficient estimate for x (including SE). Also the residual standard error is the same. The same result is produced when I simulate some missing data:
# simulate missing data
y[c(1:(n/2), (n*k-n/2):(n*k))] <- NA
m2 <- lm(y ~ cat + x)
summary(m2)
m3 <- lme(y ~ x, random = ~ 1|cat, na.action = na.omit)
summary(m3)
So can we say in general that adding effect as random will have the same impact on the other coefficients and the overall inference as adding it as fixed? If not, can you please provide a simple example (or change the provided one) when this fails?