I have data of countries, years and some variables as shown below:
df <- structure(list(country = c(1, 1, 1, 2, 2, 2, 3, 3, 3), continent = structure(c(3L,
3L, 3L, 4L, 4L, 4L, 2L, 2L, 2L), .Label = c("Africa", "Americas",
"Asia", "Europe", "Oceania"), class = "factor"), year = c(0,
1, 2, 0, 1, 2, 0, 1, 2), lifeExp = c(80.69, 82, 82.603, 77.218,
78.471, 79.425, 76.81, 77.31, 78.242), pop = c(125956499L, 127065841L,
127467972L, 58808266L, 59912431L, 60776238L, 272911760L, 287675526L,
301139947L), gdpPercap = c(28816.58499, 28604.5919, 31656.06806,
26074.53136, 29478.99919, 33203.26128, 35767.43303, 39097.09955,
42951.65309)), class = "data.frame", row.names = c(NA, -9L))
country continent year lifeExp pop gdpPercap
1 1 Asia 0 80.690 125956499 28816.58
2 1 Asia 1 82.000 127065841 28604.59
3 1 Asia 2 82.603 127467972 31656.07
4 2 Europe 0 77.218 58808266 26074.53
5 2 Europe 1 78.471 59912431 29479.00
6 2 Europe 2 79.425 60776238 33203.26
7 3 Americas 0 76.810 272911760 35767.43
8 3 Americas 1 77.310 287675526 39097.10
9 3 Americas 2 78.242 301139947 42951.65
I am interested in looking at how countries life expectancy
change with time
or year
, while adding another predictor -- a time-varying covariate, which is gdpPercap
. I am using a step-by-step model building process by adding complexity to each successive model using the r package nlme
:
randomIntercept <- lme(lifeExp ~ 1, random=~1|country, data=df, method='ML') # random intercept model
yearRI <- lme(lifeExp ~ year, random=~1|country, data=df, method='ML') # add year as fixed effect
ARModel <- update(yearRI, correlation=corAR1()) # include first-order autocorrelation
gdp_tvc <- update(ARModel, .~. + gdpPercap) # adding gdp as time-varying covariate
I am wondering if this is the correct way to add a time-varying covariate? So my last model in full form is:
gdp_tvc <- lme(lifeExp ~ year + gdpPercap, random=~1|country, data=df, correlation=corAR1(), method='ML')