Tuesday, June 9, 2015

A simple example of mixed effects model using simulated data in R

First let's make the dataframe.

rm(list=ls())
library(lme4)
set.seed(1)
ID = c(rep('A',10), rep('B', 10), rep('c', 10))
x = c(1:10)
ya = x + 1 + rnorm(10)
yb = x + 2 + rnorm(10)
yc = x + 3 + rnorm(10)
df <- data.frame="" id="" x="rep(x,3)," y="c(ya,yb,yc))</font">

Then let's do liner regression.
mdl.lm <- span=""> lm(y~x, data=df)
coef(mdl.lm)

## (Intercept)           x
##    2.073487    1.001631

The linear regression cannot treat each ID seperately. It provides an overall intercept (2.073487) and overall slope (1.001631) for all the 30 data points.

Next, let's build a random-intercept mixed effects model.

mdl.mix.RI <- span=""> lmer(y~x+(1+1|ID),data=df, REML=F)
coef(mdl.mix.RI)

## $ID
##   (Intercept)        x
## A    1.287210 1.001631
## B    2.211162 1.001631
## c    2.722090 1.001631
##
## attr(,"class")
## [1] "coef.mer"


The above model can treat each ID differently, so the Intercept for each ID are different.

Last, let's build a random-intercept and random-slope mixed effects model.

mdl.mix.RIS <- span=""> lmer(y~x+(1+x|ID),data=df, REML=F)
coef(mdl.mix.RIS)

## $ID
##   (Intercept)         x
## A   0.9373545 1.0650834
## B   2.2293276 0.9929275
## c   3.0537802 0.9468823
##
## attr(,"class")
## [1] "coef.mer"


This model also treat each ID differently, and it gives different intercept and slope for each ID.

No comments:

Post a Comment

Any comments?

my-alpine and docker-compose.yml

 ``` version: '1' services:     man:       build: .       image: my-alpine:latest   ```  Dockerfile: ``` FROM alpine:latest ENV PYTH...