































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!
































Checking model assumptions via graphical displays of the residuals, testing linear hypotheses and model comparisons
library (car)
# Load data: file birtwt.csv dati<- read.csv ( file.choose (),sep=";") str (dati)
Dependent variable:
Candidate regressors:
Aim : we want to study whether the differences in birth weight of babies (dependent variable) can be related to some factors (regressors).
The candidate regressors are both categorical and numerical. As long as categorical regressors are coded in R with numbers we have to recode that values through the function ‘factor’.
# recoding qualitative (categorical) predictors dati $ race<- factor (dati $ race,labels= c ("white","black","other")) dati $ smoke<- factor (dati $ smoke,labels= c ("no","yes")) dati $ ht<- factor (dati $ ht,labels= c ("no","yes")) dati $ ui<- factor (dati $ ui,labels= c ("no","yes"))
str (dati)
# graphical bivariate plots: examples for exploring data plot (bwt ~ lwt,data=dati) # scatter plot plot (bwt ~ race,data=dati) # box plot
100 150 200 250
1000
2000
3000
4000
5000
lwt
bwt
white black other
1000
2000
3000
4000
5000
race
bwt
Fitting a Gaussian multiple linear regression model including all the regressors
model1<- lm (bwt ~ .,data=dati)
summary (model1)
NB. The dispersion parameter is the unbiased estimate for the variance (in fact: 650.3ˆ2 = 422918). The AIC is important to compare models with different assumptions. While the null deviance is the total sample deviance of y, the residual deviance is the sum of the squared residuals (SSE). So that the dispersion parameter is also SSE divided by n-p=179.
Checking the adequacy of the model assumptions via graphical displays of the residuals
1. Linearity of the conditional expected value
# residuals vs fitted plot plot (model1, which=1)
2000 2500 3000 3500
−
0
1000
2000
Fitted values
Residuals
lm(bwt ~ .)
Residuals vs Fitted
132
130
136
When the linearity assumption is adequate, it is reasonable to think that the expected birth weight is a linear combination of the values of the 8 regressors that we have included in the model. As a result, we would expect a plot in which the residuals are scattered in an even way, both below and above zero.
In this plot there isn’t any systematic pattern. In fact, whatever the fitted value is, there are always some positive and negative residuals. Recalling that by construction the residuals sum up to zero, we have that negative and positive residuals tends to cancel out and there is an average that tends to zero. This red line is a moving (local) average of the residuals computed for unit with a fitted value that falls in a limited range. Here we are summing the residuals only for units with similar fitted values. In conclusion, the linearity assumption of the expected birth weight given the 8 regressors is reasonable and adequate.
2. Normality of the conditional distributions
# quantile-quantile plot plot (model1,which=2)
−3 −2 −1 0 1 2 3
−
−
−
0
1
2
3
Theoretical Quantiles
Standardized residuals
lm(bwt ~ .)
Q−Q Residuals
132
130
136
Comparison between the standardized residuals with theoretical quantiles. If the model assumptions are adequate, the standardized residuals should look like a sample taken from a standard Gaussian distribution.
In the plot, there are the empirical/observed quantiles for the standardized residual on the vertical axis and on the horizontal axis there are the theoretical ones from a standard Gaussian distribution. If the empirical distribution is similar to a theoretical one, the points should be aligned along a line. Although there is some variability for the lower and higher values, for most of the data points there is an alignment. There is a straight pattern at least between -2 and 2, so that the normality assumption is considered adequate.
3. Homoscedasticity (same variance) of the conditional distributions
# scale-location plot plot (model1, which=3)
d1<- rep (0,9) #sequence of zeros
lht (model1,C1,d1)
# lht(model1,C1) the result is the same
The coefficient associated to each of these regressors are simultaneously set equal to zero. 188 = degrees of freedom of the model containing only the intercept (n-1) 179 = degrees of freedom of the fitted model with the 10 coefficients (n-10) 9 = difference in the degrees of freedom, number of rows of the matrix C Recall that this F-test statistic and the corresponding p-value are exactly the same of those in the fitted model with ‘lm’ because by default it computes the linear independence hypothesis.
2. F statistic with Anova function
The F test statistic can also be used in case of nested models.
A possibility it is comparing the full model with all the regressors and a restricted model containing only the intercept. Firstly, we have to build a nested model. Secondly, we should directly compare these two models with the function ‘anova’.
# update the model by changing its formula (all the regressors -> only the intercept) model2<- update (model1,. ~ 1)
summary (model2)
In model 2, we do not have the F-test statistic because there are not regressors. It is the model that assumes that the average birth weight (y) is constant irrespective of the values of the regressors. Incidentally, this intercept is nothing but the sample mean of the dependent variable.
Compute the F-test statistic with the function ‘anova’. It produces several test statistics which are based on the decomposition of the deviance. If you apply the anova function to two models, we put the constrained model as first argument and the unconstrained model as second model, we will get the exact output of the one obtained with the independence linear hypothesis.
anova (model2,model1)
In conclusion, we have at least three different ways to compute the linear independence hypothesis (lm, lht, anova).
3. F statistic with Anova function to test only some regressors
If we look at the plots of the race, there seems to be same differences in the average birth weight, but the main difference is between caucasian origins vs all the others. There seems to be not a big difference between afroamerican women and women with others ethnicity. Consequently, we can exploit the linear hypothesis to check if there significant differences in the average birth weight for babies born from afroamerican women and others ethnicity.
The F-test statistic produced with this anova function is exactly the same F-test statistic that we obtain with the lht function.
Additionally, we can compare the adjusted R-squared to compare the two models.
summary (model1) $ adj.r.squared
summary (model4) $ adj.r.squared
The model with fewer regressors has an higher adjusted R-squared than the unconstrained model. This simplification allows to reach a better compromise between adequacy and complexity.
4. Compare non-nested models
In this case we want to compare two non-nested models. We generate a model by removing the regressors ‘age’ and ‘ftv’ and we compare it with the best model found before.
model3<- update (model1,. ~. - age - ftv) model
model
Two functions in R to compute AIC to compare non-nested models (instead of the adjusted R-squared):
AIC (model3)
AIC (model4)
extractAIC (model3)
extractAIC (model4)
The difference in the output of these two functions is related to the terms in the definition of the AIC that do not depend on the parameters, but that depends only on the sample size. In fact, two different formulas to compute AIC exist: one complete and a simplified one that can used with Gaussian linear models. They differ only due to a constant depending on the sample size. When applied to an object created using ‘lm’ function, extractAIC computes a simplified expression, where terms in the log-likelihood not depending on model parameters are ignored and sigmaˆ2 is not taken into account when determining the complexity. As a result, if we compute the difference between AIC and extractAIC we obtain a constant, which is the same for both models.
AIC (model3) -extractAIC (model3)[2]
AIC (model4) -extractAIC (model4)[2]
NB: It is possible to compute the BIC from the extractAIC function by substituting the argoment k=2 with k=ln(n)
Regressors:
Dataset with 108 level 1 units divided in 27 level 2 units (‘Subject’). The ‘Subject’ can interpreted as a level 2 unit, it is included in the model as a random factor. The regressor ‘age’ is a level 1 regressor and ‘Sex’ is level 2 regressor.
Aim : we want to study the effects of random effect in studying the distance between the pituitary gland and the pterygomaxillary fissure.
Recode Subject and Sex as categorical variables. As long as categorical regressors are coded in R with numbers we have to recode that values through the function ‘factor’. Additionally, center ‘age’ equal to 11 years old.
ortho $ Subject<- factor (ortho $ Subject) ortho $ Sex<- factor (ortho $ Sex)
ortho $ age<-ortho $ age-
Preliminary data management and explorative analysis through graphical displays
Create a groupedData object, a function which allows to explicitly tell R that the dataset has a multilevel structure. A groupedData can be created by assigning a formula to a dataframe, this formula states the dependent variable and categorical variable representing the random factor (‘Subject’). The formula may contain level 1 regressors (‘age’). Level 2 regressors (‘Sex’) instead, can be added using the argument outer. (it is advisable to add only categorical regressors through this argument).
ortho1<- groupedData (distance ~ age | Subject,outer= ~ Sex,data=ortho)
The formula in a groupedData object is used by default to create graphical displays of the data
plot (ortho) # dataframe without formula - all variables are displayed
− −
1
3
20 25 30
−3 −1 0 1 2 3
0 5 10 15 20 25
1.0 1.4 1.
20
25
30
0
10
20
plot (ortho1)
age
distance
20
25
30
−3 0 2
F10 F
−3 0 2
F06 F
−3 0 2
F05 F
−3 0 2
F07 F
−3 0 2
F03 F
−3 0 2
F11 M
−3 0 2
M16 M
M
−3 0 2 M14 M
−3 0 2 M07 M
−3 0 2 M04 M
−3 0 2 M06 M
−3 0 2 M15 M
−3 0 2 M
20
25
30
M
plot (ortho1, outer = TRUE, key= FALSE, aspect=1.5)
age
distance
20
25
30
−3 −2 −1 0 1 2 3
Female
−3 −2 −1 0 1 2 3 Male
The plot for the original dataframe is a scatter plot matrix. Each scatter plot with a pair of variables. The plot with groupedData recognise the formula, and create a plot much more meaningful plot. There is a box for each child (random factor), and for each of this level 2 unit you have the dependent variable and the level 1 regressor (age). The last plot, with the outer=T argument, explicitly create two box with the level 2 regressor ‘Sex’; one box for male and one for female. There is a growth pattern as the age increases. Remember that age is centered on 11 years old. NB: for more complicated dataset you can add more than 1 regressor.
Another way is looking at the ‘intervals’, obtaining not only the estimated intercepts and regression coefficient for age, but also confidence intervals associated to each parameter.
head ( intervals (lmList1))
plot ( intervals (lmList1))
Subject
F F
F F F F
F F F F
F M M M
M M M M
M M M
M M M M
M M
20 25 30
|
| | | |
| | | |
| | |
| | | |
| | | |
| | | |
| | |
|
| | | |
| | | |
| | |
| | | |
| | | |
| | | |
| | |
|
| | | |
| | | |
| | |
| | | |
| | | |
| | | |
| | |
(Intercept)
−0.5 0.0 0.5 1.0 1.5 2.0 2.
|
| | | |
| | | |
| | |
| | | |
| | | |
| | | |
| | |
|
| | | |
| | | |
| | |
| | | |
| | | |
| | | |
| | |
|
| | | |
| | | |
| | |
| | | |
| | | |
| | | |
| | |
age
Confidence intervals for intercepts and age effects are only partially overlapping: it is reasonable to include a random effect for both parameters. In particular, some pairs of confidence intervals for the intercept do not overlap; consequently, there is a significant impact of the factor Subject on the intercept. Intercepts can be interpreted as the average distance at age 11. The overlapping in age is much more substantial, but some degree of non overlap can also be spotted.
Gaussian linear mixed model fitting
Fit a Gaussian linear mixed model with - fixed effects for sex (level two regressor), - a random intercept,
The function is ‘lme’, linear mixed-effects models, is lme(fixed, data, random, correlation, weights, method). The first element ‘fixed’ includes the regressors with fixed effect. The second element ‘data’ specificies the dataset. The third element ‘random’ includes the variable of the random factors and define the regressors for which we want the random effects. The elements ‘correlation’ and ‘weigths’ can be used to define the correlation and the heteroscedasticity structure for the random error (extended Gaussian linear mixed model). The last element ‘method’ define whether we want estimate the variane parameter through the profile ML or the restricted ML (by default the method is REML).
lmm1<- lme (fixed=distance ~ age + Sex,random= ~ age | Subject,data=ortho1) # or, equivalently lmm1b<- lme (fixed=distance ~ age + Sex,random= ~ age,data=ortho1)
NOTE THAT: since ortho1 already contains a formula that identifies the random factor, it is not necessary to add this information in the “random” argument.
Extract the ML estimate for the fixed effect with ‘fixef’, in particular the population intercept, the population regression coefficient for age and the effect for sex (average between male and female, after fixing the age).
# estimated fixed effects fixef (lmm1)
Fixed effect: intercept 22.75 = average measurement for a female child at 11 years old (age=0 and sex=0) SexMale 2.14 = when you compare two children with the same age, there is a tendency for male to show larger value in the distances (positive value) age 0.66 = population regression coefficient for age
It is possible to extract the predicted values for random effects with ‘ranef’.
# predicted values for random effects head ( ranef (lmm1))
There are information for the random effects, and ‘structure’ refers to the Q-matrix and in this case it is a general positive-definite 2x2 matrix which is not diagonal. Under that, there are information about the estimate of the variance parameters. In particular, StdDev for the random effect, and Corr for random effect (correlations instead of covariances). The fixed effect summary is similar to the one for Gaussian linear model with the estimates for the Beta coefficients, the standard error, the degrees of freedom for the denominator of the F-test statistic (g2), t-value and p-value. The value for DF is different between the intercept and age (80) and Sexmale (25), because there are different formula for level 1 regressor (n-m-k1) and level 2 regressor (m-k2-1).
Moreover, here a graphical comparison using the function ‘augPred’, to compute the fitted values associated to the model. In this case, these fitted line are obtained using the new coefficients for Gaussian linear mixed model. The main advantage is that there are less number of parameters (only 5 parameters instead of 54 parameters).
plot ( augPred (lmm1),layout= c (9,3))
age
distance
20
25
30
−3−1 123
F10 F
−3−1 123
F06 F
−3−1 123
F05 F
−3−1 123
F07 F
−3−1 123
F
F04 F11 M11 M16 M08 M05 M14 M
20
25
30
M
20
25
30
M
−3−1 123 M04 M
−3−1 123 M06 M
−3−1 123 M15 M
−3−1 123 M09 M
Hypothesis testing on fixed effects
Recall that, in the summary, the t-test statistics explore whether each specific fixed effect is significantly different from 0 or not. They test the H 0 : betaj = 0
The same test statistics can be obtained using the anova function. If you supply the anova function with an object created with the lme function, you will have different results. The fisrt argument is the model computed through the lme function, the second argument is type=“marginal”.
anova (lmm1,type="marginal")
NOTE THAT: the difference in the degrees of freedom and the p-value are the same as in the summary of the model. In particular, the connection is t^2 = F.
The anova function allows to test arbitrary linear systems of hypotheses on the fixed effects, by supplying a proper L argument (setting C and d). The limitation of the anova function is that it allows to test a limited sets of linear restrictions. In particular, you can set the matrix C, but d is by default 0 and you cannot change it. The other strong limitation is that you cannot define system of linear hypotheses involving both level 1 and level 2 regressors. Consequently, if we want to test the linear independence hypothesis we cannot use the anova function but the likehood ratio test statistic.
This matrix C test whether there is a significant impact of ‘Sex’ on the dependent variable.
C<- matrix ( c (0,0,1),1,3) anova (lmm1,L=C)
NOTE THAT: if we create a matrix C to test both the level 1 regressor and the level 2 regressor, the anova function will give us an error.
So that, we compute the likelihood ratio test statistic to test the linear indipendent hypothesis. When testing linear hypotheses on the fixed effects, the complete and reduced models should be fitted using the profile maximum likelihood method, not the restricted one (by default). Consequently, we have to update the model, using the profile maximum likelihood method. Then, we create a second model in which we update the fixed effect by removing ‘Sex’ and ‘age’. Finally, we apply the anova function with the two models.
lmm1ML<- update (lmm1,method="ML") lmm1MLH0<- update (lmm1ML, fixed=. ~. - Sex - age)
anova (lmm1MLH0,lmm1ML)
There is a likelihood ratio test statistic that allows to compare the model with both the effect of age and gender, and a second model without the two regressors containing only the intercept. The hypothesis should be rejected because the p-value is very small, so that it is better to mantain the fixed effect in the model.
NOTE THAT: it is possible to compare the complete model with another model only without ‘Sex’ or ‘age’ (and we will have the result of the anova with the matrix C). The hypotheses are rejected as well.
Models with uncorrelated random effects (diagonal D)
Create a model with uncorrelated random effect by modifying the matrix Q, which is by default full positive- definite (diagonal element different from 0). With ‘pdDiag’ we modify the Q matrix in order to have a diagonal matrix, with covariances equal to 0 and uncorrelated random effects. In general the matrix Q can be update with pdClasses which contains all the possible structures (for example: pdIden = identity matrix with also same variance, pdCompSym = compound simmetry structure).
In the original model lmm1, the estimate for the correlation betweent the two random effects is low. Conse- quently, we try to change the matrix Q with uncorrelated random effects. In order to impose out diagonal elements equal to 0, we have to apply the pdDiag function to the random argument ‘age’.