Welcome to the Analyzing Continuous Data Unit! In this series of lessons, we are looking at how to do various common statistical tests in R, leading to more complex data and modelling approaches.
In the previous Unit, we have looked at solely categorical data (Testing Ratios) and continuous data from categories (Testing Populations).
In this lesson, we will look at methods to test whether two or more samples of continuous data are positively or negatively associated. We will also consider having multiple predictor variables. Our fundamental question is:
For categorical variables, we can use a Chi-Squared test of association. See the Testing Ratios lesson for more details.
Consider that we have two (2) continuous variables. A first question might be: ‘Do these samples come from the same distribution?’ we can use a Kolmogorov-Smirnov Test to answer this.
The function ks.test()
performs a two-sample test of the null hypothesis that x and y were drawn from the same continuous distribution.
Let’s generate some random data that we can use to test this function. Use the function rnorm()
to generate 50 values drawn randomly from a normal distribution. rnorm()
requires the number of samples (n =
). You can also change the mean and standard deviation. In this case, just generate 50 values with the defaults (mean of 0 and sd of 1). Assign this to x
.
x <- rnorm(50)
Now, generate a vector of 50 values from a uniform distribution using runif()
, and assign this to y
.
y <- runif(50)
Feel free to use hist()
at any point if you’re curious how a normal and uniform distribution vary.
The ks.test()
function takes x =
and y =
. Put our two new objects in there and test if they are from the same distribution.
ks.test(x, y)
##
## Two-sample Kolmogorov-Smirnov test
##
## data: x and y
## D = 0.42, p-value = 0.000246
## alternative hypothesis: two-sided
The p-value less than 0.001 suggests that x and y are indeed drawn from different distributions (as we suspected … ).
Whether we run correlation or a regression depends on how we think the two variables are related. If we think that there is no causal relationship between the two, then we would test for a correlation. If we think that there is a causal relationship between the two, then we would run a regressin.
As they saying goes ‘correlation does not imply causation’.
The function cor()
returns the correlation coefficient of two variables. It requires an x =
and a y =
, and a method =
. Pearson’s product moment correlation coefficient (method = 'pearson'
) is the parametric version used for normal data (and the default). Kendall’s tau (method = 'kendall'
) or Spearman’s rho (method = 'spearman'
) are used for non-parametric data.
The function cor.test()
tests for association—correlation—between paired samples, using one of Pearson’s product moment correlation coefficient, Kendall’s tau, or Spearman’s rho, as above. The three methods each estimate the association between paired samples and compute a test of the value being zero (indicating no association).
In the New Haven Road Race data, it would seem sensible that Net time and Pace are correlated.
The race data are loaded with the lesson as race
. Calculate the correlation coefficient of Net time and Pace.
cor(x = race$Nettime_mins, y = race$Pace_mins)
## [1] 0.9953277
Now test if this correlation coefficient is greater than 0 with cor.test()
.
cor.test(x = race$Nettime_mins, y = race$Pace_mins)
##
## Pearson's product-moment correlation
##
## data: race$Nettime_mins and race$Pace_mins
## t = 529.66, df = 2640, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
## 0.9949582 0.9956703
## sample estimates:
## cor
## 0.9953277
As usual, you can assign this to an object, and extract the various parts of the object, such as the coefficient, p-value, etc.
Ok, now we are coming to one of the most commonly used statistical models. If we think that one variable/s is driving variation in the other, we should use regression rather than correlation.
The function lm()
is used to develop linear models. At its simplest, it takes one argument: formula =
. This argument is the first one, and so folks rarely even write out the formula =
part.
However, this formula is how models (i.e., statistical relationships between variables) are specified, symbolically. A typical model has the form response ~ terms
, where response
is the response (or dependent) variable and terms
is (a series of) term/s which specifies a linear predictor (or independent) variable.
The response variable is fitted as a function of the predictor variable. You have used this already with the tilde symbol (~
), which signifies ‘as a function of’, and separates the response and predictor variables. Adding further predictor variables to the right hand side is also possible (see Formulae).
For now, we will carry out a simple regression of a single predictor and response. This model estimates values for the three elements of the equation: y ~ beta0 + beta1 * x + sigma.
In other words: y ~ intercept + slope * x + sd of the error. We will come back to this later.
We will illustrate the use of lm()
using the sparrow data, loaded with this lesson (even though we know there is actually no causality here).
First, as always, look at the data. Display the head of the sparrow data, sparrow
.
head(sparrow)
## Species Sex Wingcrd Tarsus Head Culmen Nalospi Wt Observer Age
## 1 SSTS Male 58.0 21.7 32.7 13.9 10.2 20.3 2 0
## 2 SSTS Female 56.5 21.1 31.4 12.2 10.1 17.4 2 0
## 3 SSTS Male 59.0 21.0 33.3 13.8 10.0 21.0 2 0
## 4 SSTS Male 59.0 21.3 32.5 13.2 9.9 21.0 2 0
## 5 SSTS Male 57.0 21.0 32.5 13.8 9.9 19.8 2 0
## 6 SSTS Female 57.0 20.7 32.5 13.3 9.9 17.5 2 0
Second, let’s plot the data that we want to model. Plot Tarsus as a function of Wingcrd, making sure that you use a formula and the data =
argument.
plot(Tarsus ~ Wingcrd, data = sparrow)
It looks like there is a positive relationship between the two. Ok, now we are ready to run the actual model. Call the output m0
, and use lm()
to model Tarsus as a function of Wingcrd. Notice that you can use almost the same code as you used to plot the data.
m0 <- lm(Tarsus ~ Wingcrd, data = sparrow)
Ok, so our model is stored in the object m0
. We can use several functions to extract all or part of this object. As usual, we can use str()
to look at everything contained in the model object m0
. Try that.
str(m0)
## List of 12
## $ coefficients : Named num [1:2] 8.374 0.226
## ..- attr(*, "names")= chr [1:2] "(Intercept)" "Wingcrd"
## $ residuals : Named num [1:979] 0.1935 -0.0669 -0.733 -0.433 -0.2801 ...
## ..- attr(*, "names")= chr [1:979] "1" "2" "3" "4" ...
## $ effects : Named num [1:979] -671.968 16.218 -0.74 -0.44 -0.285 ...
## ..- attr(*, "names")= chr [1:979] "(Intercept)" "Wingcrd" "" "" ...
## $ rank : int 2
## $ fitted.values: Named num [1:979] 21.5 21.2 21.7 21.7 21.3 ...
## ..- attr(*, "names")= chr [1:979] "1" "2" "3" "4" ...
## $ assign : int [1:2] 0 1
## $ qr :List of 5
## ..$ qr : num [1:979, 1:2] -31.289 0.032 0.032 0.032 0.032 ...
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : chr [1:979] "1" "2" "3" "4" ...
## .. .. ..$ : chr [1:2] "(Intercept)" "Wingcrd"
## .. ..- attr(*, "assign")= int [1:2] 0 1
## ..$ qraux: num [1:2] 1.03 1.02
## ..$ pivot: int [1:2] 1 2
## ..$ tol : num 1e-07
## ..$ rank : int 2
## ..- attr(*, "class")= chr "qr"
## $ df.residual : int 977
## $ xlevels : Named list()
## $ call : language lm(formula = Tarsus ~ Wingcrd, data = sparrow)
## $ terms :Classes 'terms', 'formula' language Tarsus ~ Wingcrd
## .. ..- attr(*, "variables")= language list(Tarsus, Wingcrd)
## .. ..- attr(*, "factors")= int [1:2, 1] 0 1
## .. .. ..- attr(*, "dimnames")=List of 2
## .. .. .. ..$ : chr [1:2] "Tarsus" "Wingcrd"
## .. .. .. ..$ : chr "Wingcrd"
## .. ..- attr(*, "term.labels")= chr "Wingcrd"
## .. ..- attr(*, "order")= int 1
## .. ..- attr(*, "intercept")= int 1
## .. ..- attr(*, "response")= int 1
## .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
## .. ..- attr(*, "predvars")= language list(Tarsus, Wingcrd)
## .. ..- attr(*, "dataClasses")= Named chr [1:2] "numeric" "numeric"
## .. .. ..- attr(*, "names")= chr [1:2] "Tarsus" "Wingcrd"
## $ model :'data.frame': 979 obs. of 2 variables:
## ..$ Tarsus : num [1:979] 21.7 21.1 21 21.3 21 20.7 22 20.8 20.1 22.2 ...
## ..$ Wingcrd: num [1:979] 58 56.5 59 59 57 57 57 57 53.5 56.5 ...
## ..- attr(*, "terms")=Classes 'terms', 'formula' language Tarsus ~ Wingcrd
## .. .. ..- attr(*, "variables")= language list(Tarsus, Wingcrd)
## .. .. ..- attr(*, "factors")= int [1:2, 1] 0 1
## .. .. .. ..- attr(*, "dimnames")=List of 2
## .. .. .. .. ..$ : chr [1:2] "Tarsus" "Wingcrd"
## .. .. .. .. ..$ : chr "Wingcrd"
## .. .. ..- attr(*, "term.labels")= chr "Wingcrd"
## .. .. ..- attr(*, "order")= int 1
## .. .. ..- attr(*, "intercept")= int 1
## .. .. ..- attr(*, "response")= int 1
## .. .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
## .. .. ..- attr(*, "predvars")= language list(Tarsus, Wingcrd)
## .. .. ..- attr(*, "dataClasses")= Named chr [1:2] "numeric" "numeric"
## .. .. .. ..- attr(*, "names")= chr [1:2] "Tarsus" "Wingcrd"
## - attr(*, "class")= chr "lm"
There is a lot in there! Given that it is a list, we can access any part of it as we would any other list. For example, we could use m0$coefficients
to pull out the model coefficients. Try that.
m0$coefficients
## (Intercept) Wingcrd
## 8.3738466 0.2264258
There are also a number of generic functions that are built to work on any model object. One of these generic functions is coef()
, which we can use to pull out the coefficient estimates of the model. Try putting m0
in a call to coef()
.
coef(m0)
## (Intercept) Wingcrd
## 8.3738466 0.2264258
Both m0$coefficients
and coef(m0)
return a (identical) named vector: The names of each coefficient estimate are given for each element of the vector. The intercept is the intercept, i.e., when x = 0, at what point the regression line crosses the y-axis. The slope of the regression line is given by the element named for the predictor variable in the model (in this case Wingcrd). The slope means for a unit change in x, what the change in y is. In this case, a 1-unit change in Wingcrd leads to an increase of 0.23 in Tarsus.
Let’s look at a more traditional output of the statistical model. We can use summary()
to return that. Do so.
summary(m0)
##
## Call:
## lm(formula = Tarsus ~ Wingcrd, data = sparrow)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.06691 -0.53297 -0.03297 0.42273 3.04060
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 8.37385 0.61834 13.54 <2e-16 ***
## Wingcrd 0.22643 0.01068 21.21 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.7648 on 977 degrees of freedom
## Multiple R-squared: 0.3152, Adjusted R-squared: 0.3145
## F-statistic: 449.7 on 1 and 977 DF, p-value: < 2.2e-16
Here we see several parts to the model output. First, the model itself (Call), then a summary of the residuals (Residuals), then details of the coefficients (Coefficients), their values, standard errors, t values, and p values. The p-values correspond to specific tests. First, the test is if the intercept is significantly different from 0. We are not too often interested in this value or significance. What we are usually more interested in is if there is indeed a positive or negative relationship between the two variables in the model. The p-value in this case tells us if the slope is significantly different from 0. In this case it is, and so we infer that as Wingcrd increases, so does Tarsus.
Below this, we also get some information on the remaining unexplained variation, R2 values, and F tests.
The other useful parts of the model that you may want to look at, at least for model-checking, are the residuals, using either m0$residuals
or the generic function residuals()
. Try either of those.
residuals(m0)
## 1 2 3 4 5
## 0.193455497 -0.066905764 -0.732970329 -0.432970329 -0.280118677
## 6 7 8 9 10
## -0.580118677 0.719881323 -0.480118677 -0.387628286 1.033094236
## 11 12 13 14 15
## 0.785945888 -0.127267025 0.319881323 -0.559396155 0.380242584
## 16 17 18 19 20
## -0.527267025 -0.732970329 -0.566905764 -0.993331590 0.306668410
## 21 22 23 24 25
## -0.559396155 -0.432970329 -0.706544503 0.372732975 -1.172609068
## 26 27 28 29 30
## 0.280242584 -0.459396155 -1.119757416 0.193455497 0.153816758
## 31 32 33 34 35
## -1.132970329 -0.132970329 -0.480118677 0.333094236 0.146307149
## 36 37 38 39 40
## -0.166905764 -0.680118677 0.093455497 -0.593331590 0.819881323
## 41 42 43 44 45
## 0.193455497 -0.140479938 -0.732970329 -1.659396155 0.340603845
## 46 47 48 49 50
## -0.132970329 0.346307149 -0.066905764 -0.580118677 0.167029671
## 51 52 53 54 55
## -0.806544503 0.572732975 -0.232970329 -0.206544503 -1.132970329
## 56 57 58 59 60
## -0.866905764 0.314178019 -0.559396155 -1.132970329 0.167029671
## 61 62 63 64 65
## -0.093331590 -0.732970329 -0.346183242 -0.959396155 -0.519757416
## 66 67 68 69 70
## 0.693455497 -0.285821981 0.440603845 0.367029671 -0.872609068
## 71 72 73 74 75
## -0.066905764 0.419881323 -1.100841199 -0.132970329 -0.100841199
## 76 77 78 79 80
## -0.600841199 0.706668410 -0.332970329 -0.332970329 -0.246183242
## 81 82 83 84 85
## -0.232970329 -0.332970329 -0.272609068 -0.032970329 0.219881323
## 86 87 88 89 90
## -0.819757416 0.333094236 -0.885821981 0.367029671 0.293455497
## 91 92 93 94 95
## 0.140603845 0.133094236 -1.019757416 -0.059396155 -0.006544503
## 96 97 98 99 100
## -0.132970329 -0.859396155 0.199158801 -1.027267025 -0.300841199
## 101 102 103 104 105
## -1.453692851 -0.053692851 -0.700841199 -0.732970329 0.072732975
## 106 107 108 109 110
## -0.353692851 -1.006544503 0.125584627 -0.527267025 -1.040479938
## 111 112 113 114 115
## 0.300965106 0.993455497 -0.859396155 -1.185821981 -0.159396155
## 116 117 118 119 120
## 0.172732975 -0.740479938 0.267029671 0.472732975 0.240603845
## 121 122 123 124 125
## -0.512247807 -0.759396155 -0.606544503 -0.140479938 -1.180118677
## 126 127 128 129 130
## 0.806668410 0.506668410 -0.193331590 -0.506544503 -0.172609068
## 131 132 133 134 135
## 0.080242584 -0.606544503 0.233094236 -0.559396155 0.019881323
## 136 137 138 139 140
## -0.685821981 0.006668410 0.419881323 0.193455497 -0.559396155
## 141 142 143 144 145
## -0.753692851 0.867029671 -1.327267025 -0.072609068 -1.206544503
## 146 147 148 149 150
## 0.846307149 0.799158801 0.072732975 0.680242584 -0.059396155
## 151 152 153 154 155
## -0.659396155 -0.819757416 -0.306544503 -1.246183242 -0.532970329
## 156 157 158 159 160
## 0.346307149 -1.632970329 0.019881323 -1.119757416 0.240603845
## 161 162 163 164 165
## 0.167029671 -0.132970329 -0.532970329 -0.959396155 -0.885821981
## 166 167 168 169 170
## -0.732970329 -1.232970329 -0.200841199 -0.200841199 -0.759396155
## 171 172 173 174 175
## -0.932970329 0.067029671 -0.053692851 -0.046183242 -0.127267025
## 176 177 178 179 180
## -1.380118677 -0.053692851 -0.959396155 0.299158801 -0.400841199
## 181 182 183 184 185
## -0.853692851 0.167029671 -0.040479938 -0.614054112 -0.706544503
## 186 187 188 189 190
## 0.019881323 -0.532970329 0.072732975 -0.580118677 -0.353692851
## 191 192 193 194 195
## -0.059396155 -0.119757416 -0.459396155 -0.185821981 -0.385821981
## 196 197 198 199 200
## 0.546307149 -0.885821981 0.267029671 0.467029671 -0.599034894
## 201 202 203 204 205
## -0.019757416 -0.232970329 -0.359396155 0.659520062 -1.166905764
## 206 207 208 209 210
## 0.672732975 -0.600841199 0.846307149 0.872732975 -0.053692851
## 211 212 213 214 215
## -0.340479938 -0.080118677 -0.253692851 1.093455497 -0.432970329
## 216 217 218 219 220
## -0.346183242 -0.453692851 -0.059396155 0.167029671 0.267029671
## 221 222 223 224 225
## 0.053816758 -0.399034894 -0.232970329 -0.606544503 -1.132970329
## 226 227 228 229 230
## -0.614054112 -0.727267025 -0.580118677 -1.053692851 0.953816758
## 231 232 233 234 235
## 0.072732975 -2.066905764 0.393455497 -0.606544503 0.972732975
## 236 237 238 239 240
## -1.059396155 -0.080118677 0.540603845 -0.432970329 0.399158801
## 241 242 243 244 245
## -0.840479938 -0.885821981 0.246307149 -1.332970329 -1.080118677
## 246 247 248 249 250
## -0.280118677 -0.053692851 -0.480118677 -0.453692851 0.146307149
## 251 252 253 254 255
## -1.346183242 -0.606544503 -1.580118677 0.533094236 -0.906544503
## 256 257 258 259 260
## -0.340479938 -0.500841199 -0.606544503 0.293455497 -1.227267025
## 261 262 263 264 265
## -1.832970329 0.085945888 1.953816758 0.308474715 1.240603845
## 266 267 268 269 270
## 0.074539280 0.680242584 -0.238673633 1.548113454 1.400965106
## 271 272 273 274 275
## 0.655623063 0.214178019 1.367029671 1.567029671 0.361326367
## 276 277 278 279 280
## 1.667029671 1.514178019 1.600965106 0.087752193 -0.178312372
## 281 282 283 284 285
## -0.138673633 1.719881323 0.114178019 0.019881323 0.061326367
## 286 287 288 289 290
## 1.219881323 2.253816758 -0.917951111 1.034900541 2.487752193
## 291 292 293 294 295
## 2.140603845 -1.359396155 0.314178019 2.433094236 0.800965106
## 296 297 298 299 300
## 1.140603845 2.114178019 0.053816758 0.225584627 0.080242584
## 301 302 303 304 305
## 0.493455497 -0.559396155 -0.459396155 -0.419757416 -0.006544503
## 306 307 308 309 310
## -0.232970329 -0.180118677 0.519881323 0.067029671 0.033094236
## 311 312 313 314 315
## -0.659396155 -0.166905764 -0.359396155 1.246307149 0.393455497
## 316 317 318 319 320
## 0.846307149 0.599158801 0.959520062 0.406668410 0.659520062
## 321 322 323 324 325
## -0.906544503 0.293455497 -0.032970329 0.653816758 0.546307149
## 326 327 328 329 330
## -0.246183242 0.219881323 -0.480118677 0.093455497 0.067029671
## 331 332 333 334 335
## -1.046183242 0.159520062 -0.146183242 -0.180118677 -0.127267025
## 336 337 338 339 340
## 0.272732975 -0.506544503 -0.080118677 -1.159396155 0.993455497
## 341 342 343 344 345
## 0.519881323 0.419881323 -0.232970329 0.367029671 -0.506544503
## 346 347 348 349 350
## -0.046183242 0.333094236 -0.006544503 0.672732975 -0.719757416
## 351 352 353 354 355
## -0.346183242 0.467029671 0.040603845 0.067029671 0.499158801
## 356 357 358 359 360
## 0.046307149 -0.080118677 0.519881323 0.106668410 0.372732975
## 361 362 363 364 365
## 0.733094236 0.293455497 0.419881323 -1.372609068 -0.346183242
## 366 367 368 369 370
## 0.572732975 0.067029671 0.140603845 -0.485821981 -1.032970329
## 371 372 373 374 375
## 0.840603845 1.119881323 1.019881323 -0.632970329 0.299158801
## 376 377 378 379 380
## -0.780118677 0.167029671 -0.232970329 -0.840479938 -0.280118677
## 381 382 383 384 385
## 1.472732975 0.267029671 0.193455497 0.319881323 0.659520062
## 386 387 388 389 390
## 0.293455497 0.293455497 0.493455497 0.093455497 -0.553692851
## 391 392 393 394 395
## -0.259396155 0.067029671 -0.006544503 -0.646183242 0.859520062
## 396 397 398 399 400
## 0.480242584 0.646307149 0.246307149 0.067029671 0.459520062
## 401 402 403 404 405
## 1.572732975 0.080242584 0.080242584 -0.532970329 0.172732975
## 406 407 408 409 410
## -0.259396155 0.453816758 0.493455497 0.280242584 0.846307149
## 411 412 413 414 415
## 0.246307149 -0.180118677 -0.032970329 -0.206544503 0.372732975
## 416 417 418 419 420
## 0.199158801 0.872732975 0.625584627 0.772732975 -0.206544503
## 421 422 423 424 425
## 0.353816758 0.772732975 0.999158801 0.485945888 -0.227267025
## 426 427 428 429 430
## -1.006544503 0.693455497 0.346307149 -0.693331590 0.172732975
## 431 432 433 434 435
## -0.706544503 -0.206544503 -0.946183242 0.846307149 -0.232970329
## 436 437 438 439 440
## -0.032970329 -0.732970329 1.085945888 0.485945888 0.219881323
## 441 442 443 444 445
## -1.632970329 -0.153692851 -0.114054112 1.538797540 -0.419757416
## 446 447 448 449 450
## -0.780118677 0.246307149 -0.127267025 0.846307149 1.099158801
## 451 452 453 454 455
## 0.233094236 -0.106544503 1.372732975 -0.959396155 -1.046183242
## 456 457 458 459 460
## 0.819881323 0.753816758 1.093455497 -0.206544503 0.699158801
## 461 462 463 464 465
## -0.346183242 0.393455497 -1.080118677 1.146307149 0.506668410
## 466 467 468 469 470
## 0.093455497 0.799158801 -0.059396155 -0.132970329 -0.432970329
## 471 472 473 474 475
## -0.419757416 -0.019757416 -0.885821981 -0.832970329 -1.519757416
## 476 477 478 479 480
## 0.119881323 0.119881323 -0.385821981 -0.593331590 -0.066905764
## 481 482 483 484 485
## 0.846307149 -0.246183242 -1.006544503 0.519881323 0.080242584
## 486 487 488 489 490
## 0.619881323 0.093455497 0.180242584 -0.253692851 -0.327267025
## 491 492 493 494 495
## 1.499158801 -1.032970329 0.672732975 -0.032970329 -0.027267025
## 496 497 498 499 500
## -0.580118677 0.559520062 0.306668410 0.119881323 0.619881323
## 501 502 503 504 505
## 0.925584627 0.167029671 1.085945888 0.367029671 0.819881323
## 506 507 508 509 510
## 0.593455497 -0.932970329 0.006668410 0.772732975 0.499158801
## 511 512 513 514 515
## -0.259396155 0.180242584 0.561326367 1.506668410 1.093455497
## 516 517 518 519 520
## 1.767029671 2.180242584 1.285945888 0.334900541 2.119881323
## 521 522 523 524 525
## 2.114178019 2.340603845 1.987752193 -0.585821981 2.327390932
## 526 527 528 529 530
## 2.161326367 0.648113454 1.167029671 1.314178019 1.187752193
## 531 532 533 534 535
## 0.748113454 1.119881323 0.519881323 1.014178019 0.814178019
## 536 537 538 539 540
## 0.387752193 1.253816758 2.219881323 0.067029671 -0.732970329
## 541 542 543 544 545
## -0.406544503 0.193455497 0.946307149 -0.432970329 -0.080118677
## 546 547 548 549 550
## 0.072732975 0.419881323 -0.659396155 -0.132970329 -0.506544503
## 551 552 553 554 555
## -0.200841199 -0.380118677 0.772732975 0.072732975 -0.559396155
## 556 557 558 559 560
## 0.119881323 0.699158801 -0.546183242 -0.553692851 -0.353692851
## 561 562 563 564 565
## 0.272732975 -0.280118677 -0.880118677 -0.140479938 0.093455497
## 566 567 568 569 570
## -0.485821981 -0.332970329 -0.966905764 0.472732975 0.172732975
## 571 572 573 574 575
## -1.206544503 -0.206544503 0.472732975 -1.246183242 0.093455497
## 576 577 578 579 580
## 0.012371714 0.067029671 0.093455497 -0.546183242 -1.332970329
## 581 582 583 584 585
## 0.485945888 -0.653692851 0.046307149 -0.353692851 -0.453692851
## 586 587 588 589 590
## -0.380118677 -0.706544503 -0.159396155 0.919881323 0.119881323
## 591 592 593 594 595
## 0.067029671 -0.380118677 -0.506544503 -0.819757416 -0.766905764
## 596 597 598 599 600
## -0.019757416 0.452010453 -1.346183242 0.019881323 -1.019757416
## 601 602 603 604 605
## -0.406544503 0.119881323 -0.106544503 -0.853692851 -1.059396155
## 606 607 608 609 610
## -0.632970329 -1.446183242 -1.180118677 0.499158801 1.761326367
## 611 612 613 614 615
## 0.387752193 1.834900541 1.087752193 1.340603845 1.214178019
## 616 617 618 619 620
## 0.908474715 2.761326367 0.348113454 0.619881323 -0.912247807
## 621 622 623 624 625
## 0.993455497 0.693455497 0.967029671 -0.332970329 -0.227267025
## 626 627 628 629 630
## 0.819881323 0.140603845 0.846307149 0.372732975 0.646307149
## 631 632 633 634 635
## 0.299158801 0.519881323 -0.227267025 0.899158801 0.619881323
## 636 637 638 639 640
## 1.199158801 -0.259396155 0.372732975 -0.653692851 0.867029671
## 641 642 643 644 645
## 0.293455497 -0.632970329 -0.280118677 1.019881323 -0.185821981
## 646 647 648 649 650
## 0.467029671 0.519881323 0.206668410 -1.270802763 0.519881323
## 651 652 653 654 655
## 1.099158801 -0.653692851 -0.506544503 -0.153692851 -0.332970329
## 656 657 658 659 660
## 0.319881323 0.572732975 0.093455497 0.246307149 -1.214054112
## 661 662 663 664 665
## 0.033094236 0.393455497 -0.732970329 -0.227267025 0.172732975
## 666 667 668 669 670
## 1.461326367 -1.172609068 -1.032970329 0.185945888 -0.232970329
## 671 672 673 674 675
## -0.440479938 0.472732975 -1.066905764 0.006668410 -0.006544503
## 676 677 678 679 680
## -0.993331590 -0.214054112 -0.680118677 -1.632970329 -0.727267025
## 681 682 683 684 685
## -0.006544503 0.199158801 0.146307149 0.099158801 -0.706544503
## 686 687 688 689 690
## -1.006544503 -1.206544503 -0.146183242 -0.446183242 -0.287628286
## 691 692 693 694 695
## 0.959520062 -0.406544503 -1.206544503 -0.393331590 -0.380118677
## 696 697 698 699 700
## -0.946183242 -0.040479938 -0.806544503 0.433094236 -1.159396155
## 701 702 703 704 705
## -0.227267025 -0.546183242 -0.080118677 -1.406544503 0.619881323
## 706 707 708 709 710
## 0.219881323 0.346307149 -0.353692851 -0.819757416 -0.400841199
## 711 712 713 714 715
## -0.466905764 -1.159396155 -0.727267025 -0.753692851 0.425584627
## 716 717 718 719 720
## 0.619881323 -0.332970329 -0.532970329 0.519881323 0.646307149
## 721 722 723 724 725
## -0.359396155 0.180242584 -0.880118677 -1.106544503 0.193455497
## 726 727 728 729 730
## 0.472732975 -0.080118677 0.467029671 -0.900841199 -0.566905764
## 731 732 733 734 735
## -0.559396155 -0.532970329 -1.159396155 -0.132970329 -0.614054112
## 736 737 738 739 740
## -0.593331590 0.533094236 -0.580118677 0.480242584 -0.180118677
## 741 742 743 744 745
## -0.280118677 0.380242584 -1.046183242 0.006668410 -0.859396155
## 746 747 748 749 750
## -0.766905764 -0.353692851 -0.080118677 -0.680118677 -0.653692851
## 751 752 753 754 755
## 0.125584627 0.633094236 -0.206544503 -0.580118677 -1.200841199
## 756 757 758 759 760
## 0.433094236 -0.393331590 -0.614054112 0.512371714 -0.232970329
## 761 762 763 764 765
## -0.780118677 -0.593331590 -0.027267025 -1.380118677 -1.006544503
## 766 767 768 769 770
## 0.119881323 -1.232970329 0.572732975 -0.406544503 0.119881323
## 771 772 773 774 775
## -0.106544503 -0.832970329 -1.232970329 -0.472609068 0.419881323
## 776 777 778 779 780
## -0.306544503 -0.119757416 -0.032970329 -0.819757416 -1.100841199
## 781 782 783 784 785
## -1.306544503 0.093455497 -0.632970329 0.106668410 -0.106544503
## 786 787 788 789 790
## -0.706544503 -0.999034894 -1.080118677 0.093455497 -0.514054112
## 791 792 793 794 795
## 0.206668410 1.540603845 1.914178019 0.312314836 1.914178019
## 796 797 798 799 800
## 2.067029671 1.014178019 -0.485821981 0.367029671 1.119881323
## 801 802 803 804 805
## -0.078312372 0.561326367 2.119881323 -0.259396155 0.253816758
## 806 807 808 809 810
## -1.325460720 -0.038673633 1.180242584 1.719881323 0.300965106
## 811 812 813 814 815
## 1.540603845 1.134900541 -0.491525285 1.206668410 0.887752193
## 816 817 818 819 820
## -0.851886546 1.987752193 0.240603845 0.961326367 0.714178019
## 821 822 823 824 825
## 1.067029671 -0.580118677 -0.466905764 -0.085821981 0.767029671
## 826 827 828 829 830
## 1.167029671 -0.346183242 -0.306544503 -0.206544503 0.072732975
## 831 832 833 834 835
## -0.193331590 -0.206544503 0.993455497 -0.327267025 -0.659396155
## 836 837 838 839 840
## -0.280118677 0.440603845 0.285945888 0.093455497 -0.246183242
## 841 842 843 844 845
## 0.093455497 -0.153692851 0.406668410 0.893455497 0.572732975
## 846 847 848 849 850
## 0.359520062 -0.959396155 -0.346183242 0.085945888 1.085945888
## 851 852 853 854 855
## -0.159396155 -1.032970329 -1.106544503 0.680242584 0.706668410
## 856 857 858 859 860
## -0.459396155 0.146307149 -0.632970329 -0.285821981 0.846307149
## 861 862 863 864 865
## 0.712371714 0.067029671 1.293455497 0.367029671 0.093455497
## 866 867 868 869 870
## -1.585821981 0.782048889 1.674539280 1.427390932 2.700965106
## 871 872 873 874 875
## 0.206668410 0.519881323 0.125584627 0.253816758 -0.046183242
## 876 877 878 879 880
## -0.606544503 0.653816758 -0.246183242 -0.132970329 0.859520062
## 881 882 883 884 885
## -0.232970329 0.067029671 0.499158801 0.733094236 0.093455497
## 886 887 888 889 890
## -0.214054112 -0.180118677 0.040603845 0.719881323 -0.340479938
## 891 892 893 894 895
## -0.614054112 0.485945888 0.106668410 0.106668410 0.280242584
## 896 897 898 899 900
## -0.332970329 0.319881323 -0.632970329 0.085945888 0.267029671
## 901 902 903 904 905
## -0.206544503 0.946307149 -0.346183242 0.119881323 0.146307149
## 906 907 908 909 910
## -1.361202460 -0.919757416 -1.353692851 -0.027267025 -1.232970329
## 911 912 913 914 915
## -0.619757416 -0.119757416 -0.532970329 -0.306544503 -0.846183242
## 916 917 918 919 920
## 0.353816758 -0.932970329 1.080242584 -0.532970329 0.840603845
## 921 922 923 924 925
## -1.072609068 0.185945888 0.706668410 0.053816758 0.206668410
## 926 927 928 929 930
## -0.053692851 -0.527267025 -0.906544503 -0.666905764 -0.640479938
## 931 932 933 934 935
## -1.246183242 0.080242584 -0.606544503 -0.119757416 -0.653692851
## 936 937 938 939 940
## 0.419881323 -0.453692851 -0.327267025 -0.146183242 -0.593331590
## 941 942 943 944 945
## -0.832970329 -0.306544503 -0.219757416 0.125584627 -1.632970329
## 946 947 948 949 950
## -1.327267025 -0.272609068 -0.227267025 1.119881323 0.546307149
## 951 952 953 954 955
## 0.046307149 -1.346183242 -0.827267025 -0.032970329 0.312371714
## 956 957 958 959 960
## -0.553692851 -0.306544503 -0.753692851 -0.006544503 0.246307149
## 961 962 963 964 965
## -0.432970329 -1.432970329 0.159520062 -0.806544503 0.799158801
## 966 967 968 969 970
## -0.832970329 -1.166905764 -0.740479938 0.187752193 1.661326367
## 971 972 973 974 975
## 1.474539280 0.893455497 3.040603845 1.633094236 1.093455497
## 976 977 978 979
## 1.040603845 1.387752193 1.480242584 1.553816758
Both of these return all residuals values for each data point … you may want to assign this to another object, e.g., m0.resid
in future, or just use them as is, if needed.
We have our plot, we have our model; now we want to combine them. Usually, you would not add non-significant fitted regression lines to a plot. This model was significant, so we can feel ok doing so. The function to add a straight line to a plot is abline()
(which I think is supposed to be pronounced ‘a-b-line’, but ‘ab-line’ rolls off the tongue much more easily to me …).
abline()
can take a variety of inputs. For plotting a fitted line, you would either provide coef =
(a vector of length two giving the intercept and slope), or a =
and b =
(the intercept and slope, as single values). Usefully, abline()
can also extract the intercept and slope automagically from a model object. Pass m0
to abline()
and watch the plotting window …
plot(Tarsus ~ Wingcrd, data = sparrow)
abline(m0)
If you look at the help page for abline()
, you will see that it has elipses (…) as its final argument. You can therefore access all the plotting commands that would affect the appearance of the line from within the call to abline()
. Lets start modifying our plotting arguments. Make another call to abline()
, but make the line twice as wide with lwd = 2
, and the color red, with col = red
.
plot(Tarsus ~ Wingcrd, data = sparrow)
abline(m0, lwd = 2, col = 'red')
In the ANOVA and simple regression models that we have run so far, they have all had a single response/dependent variable as a function of a single predictor/independent variable. But in many cases we know that there are several things that could reasonably influence the response variable. For example, species and sex could both affect sparrow size; age and sex could both influence running time.
It is straightforward to include multiple predictors in a model. We start with the simple, special (!), case of Analysis of Covariance (ANCOVA).
Statisticians realised early on that ANOVA was merely the beginning of analysing experiments—other factors apart from the experimental treatment might influence the response variable they were interested in. This issue is especially pertinent when considering change, i.e., does our experimental treatment affect growth or survival? The starting point of each sample is important. If we are measuring growth of seedlings, how big that seedling is at the start of the experiment will have a big effect on its’ growth. Moreover, if by chance all the big seedlings ended up in one treatment and the small ones in another, we may erroneously assign significance to the treatment.
Thus, analysis of variance with a continuous covariate was born (i.e., Analysis of Covariance), and we can ask if our treatment had a significant effect, accounting for the measured variation in initial conditions (seedling initial size, for example).
We can illustrate with the sparrow data, and ask if male sparrows tend to have larger heads than female sparrows. From the plot, it looks like they may do.
stripchart(sparrow$Head~sparrow$Sex,
ylab = 'Head Size', xlab = 'Sex', font.lab = 2, cex.lab = 1.5,
las = 1,
vertical = TRUE,
method = 'jitter',
col = c('darkgrey', 'red'), pch = 21)
points(x = 1:2, y = tapply(sparrow$Head, sparrow$Sex, mean),
pch = 20, cex = 3)
What does the model tell us? Nest the call to lm()
within the summary()
function, to output the result table in one line of code.
summary(lm(Head ~ Sex, data = sparrow))
##
## Call:
## lm(formula = Head ~ Sex, data = sparrow)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.5817 -0.5452 -0.1452 0.2548 3.5548
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 31.78166 0.05554 572.214 < 2e-16 ***
## SexMale 0.36356 0.06616 5.495 4.98e-08 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.9442 on 977 degrees of freedom
## Multiple R-squared: 0.02998, Adjusted R-squared: 0.02899
## F-statistic: 30.2 on 1 and 977 DF, p-value: 4.978e-08
This model suggest that male sparrows have larger heads than female sparrows. In more detail, because we called lm()
, the results show us the mean value for females ((Intercept)
) and the difference between males and females (SexMale
) (because the predictor variable is categorical).
(Note that we ran an ANOVA here with the lm()
function … crazy! … Actually, ANOVA is essentially a special case of a linear model, so we can use lm()
and aov()
interchangeably to run an ANOVA. The only real effect will be how things like summary()
work. To look at the ANOVA table after a call to lm()
, you would need to use summary.aov()
; to look at the linear model table after a call to aov()
, you would need to use summary.lm()
. Simple … )
However, we could reasonably assume that larger sparrows in general will have larger heads. Accounting for sparrow size as we compare sex might be a good idea. We can include a different measure of sparrow size, such as Tarsus length, in the model.
The simplest model we can make with two variables is an additive model. Here, we specify response ~ variable1 + variable2
. What we are actually asking is if there is a difference between the mean values of variable1 and variable2 at the intercept (i.e., testing if the fitted lines for each variable have different intercepts). Modify your previous model to add Tarsus after Sex.
summary(lm(Head ~ Sex + Tarsus, data = sparrow))
##
## Call:
## lm(formula = Head ~ Sex + Tarsus, data = sparrow)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.49966 -0.42453 0.00034 0.42574 2.46084
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 16.552598 0.522026 31.708 <2e-16 ***
## SexMale 0.001364 0.049871 0.027 0.978
## Tarsus 0.721000 0.024640 29.261 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.6895 on 976 degrees of freedom
## Multiple R-squared: 0.4833, Adjusted R-squared: 0.4822
## F-statistic: 456.4 on 2 and 976 DF, p-value: < 2.2e-16
The model summary shows that now, Sex is not significant but Tarsus is, i.e., male and female sparrows do not have significantly different Head size accounting for Tarsus size, and also that the relationship between Head and Tarsus is significant and positive. We could also think about this the other way: the relationship between Head and Tarsus is the same for males and females, i.e., there is no morphological difference between sparrow sexes.
One final detail. Run the same model within summary()
, but using aov()
instead of lm()
…
summary(aov(Head ~ Sex + Tarsus, data = sparrow))
## Df Sum Sq Mean Sq F value Pr(>F)
## Sex 1 26.9 26.9 56.63 1.19e-13 ***
## Tarsus 1 407.0 407.0 856.23 < 2e-16 ***
## Residuals 976 464.0 0.5
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Now run the same model again, but swap the places of Sex and Tarsus.
summary(aov(Head ~ Tarsus + Sex, data = sparrow))
## Df Sum Sq Mean Sq F value Pr(>F)
## Tarsus 1 434 434.0 912.863 <2e-16 ***
## Sex 1 0 0.0 0.001 0.978
## Residuals 976 464 0.5
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
You should have two ANOVA tables displayed in the console. You appear to have run the same model (Head as a function of Sex and Tarsus), yet the results are quite different.
R conducts ANOVA tests (aov()
) sequentially. Thus in the model Head ~ Tarsus + Sex
, it removes (or accounts) for the effect of Tarsus before testing for differences between the sexes. In this second model, then, the effect of Sex is not significant, which is also what we saw in the output from lm()
above (it makes no difference what order the variables are in for lm()
).
Ok, we can use this simple model structure to ask not only if males and females have different head sizes on average, but also if the relationship between Head and Tarsus differes between the sexes (i.e., are the slopes significantly different).
We can run this interaction model by replacing the +
in the model formula with a *
. Try that, modifying your previous model that used lm()
, still within summary()
.
summary(lm(Head ~ Sex * Tarsus, data = sparrow))
##
## Call:
## lm(formula = Head ~ Sex * Tarsus, data = sparrow)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.49831 -0.42447 0.00169 0.43124 2.45326
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 15.72467 0.93116 16.887 <2e-16 ***
## SexMale 1.21537 1.13177 1.074 0.283
## Tarsus 0.76020 0.04404 17.260 <2e-16 ***
## SexMale:Tarsus -0.05705 0.05313 -1.074 0.283
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.6894 on 975 degrees of freedom
## Multiple R-squared: 0.4839, Adjusted R-squared: 0.4823
## F-statistic: 304.7 on 3 and 975 DF, p-value: < 2.2e-16
Let’s walk through these results. As before, we have the model and a summary of the residuals. Next is the coefficient table.
This table shows the coefficient estimates, standard error, and the t values and associated p values for significance tests. The way that the coefficients and tests are presented are different between categorical and continuous variables.
In this case, the first row of the output ((Intercept)
) shows the mean Head size of females (‘female’ comes before ‘male’ alphanumerically). The test is whether this mean value is different from 0 (not usually that useful).
The difference between the mean Head size of males and the mean Head size of females is shown in the row indicated by SexMale
. The test is whether this difference is 0 (here, there is no significant difference). To obtain the actual mean value of male Head size, you need to add the estimate for males to the estimate for females i.e. the intercept: 15.725 + 1.215.
The other two rows in the results table describe the slopes of the two fitted relationships. The row Tarsus
shows the slope of the continuous variable (Tarsus) for the first level of the factor $Sex
(females, 0.76). The test is whether this slope is different from 0 (yes, it is).
The row indicated by Tarsus:SexMale
shows the difference in the slope between males and females. The test is whether this difference is different from 0 (i.e., do females and males have different slopes). (they don’t). To get the actual slope for males, you have to take the slope for females (0.76) and add this difference (0.76 + -0.057).
Now, let’s plot! Make a plot of Head on Tarsus. Use the data =
argument.
plot(Head ~ Tarsus, data = sparrow)
To plot the regression lines on our plot of Head ~ Tarsus, we have to extract them from the model output. Make a new model, m1, using lm()
to model Head as a function of the interaction between Sex and Tarsus.
m1 <- lm(Head ~ Sex * Tarsus, data = sparrow)
Extract the coefficients using coef()
.
coef(m1)
## (Intercept) SexMale Tarsus SexMale:Tarsus
## 15.72466830 1.21536938 0.76019705 -0.05705086
Now using the named elements of coef(m1)
, subset out the value for mean female Head size (i.e., the intercept).
coef(m1)['(Intercept)']
## (Intercept)
## 15.72467
Now extract the value for the slope of females.
coef(m1)['Tarsus']
## Tarsus
## 0.7601971
Now, put these two sections of code into a call to abline()
and add the fitted line for female sparrows to the plot, using the arguments a =
and b =
.
plot(Head ~ Tarsus, data = sparrow)
abline(a = coef(m1)['(Intercept)'], b = coef(m1)['Tarsus'])
We can modify this call to abline()
to add the fitted line for males. Remember that the two values given for males are the differences between males and females. All within a new call to abline()
, add in the calculation to obtain the absolute values for males to plot the fitted line. Make the line red.
plot(Head ~ Tarsus, data = sparrow)
abline(a = coef(m1)['(Intercept)'], b = coef(m1)['Tarsus'])
abline(a = (coef(m1)['(Intercept)'] + coef(m1)['SexMale']), b = (coef(m1)['Tarsus'] + coef(m1)['SexMale:Tarsus']), col = 'red')
Here we can see that there is a slight (but not statistically significant) difference in the relationship between Tarsus and head size between males and females.
Multiple regression allows us to see the relationship between two variables, accounting for other variables in the model.
Let’s continue with the sparrow data to illustrate this. Run an additive linear model (lm()
) of Head as a function of Wingcrd, Tarsus, Culmen and Nalospi. Assign the output to m2
.
m2 <- lm(Head ~ Wingcrd + Tarsus + Culmen + Nalospi, data = sparrow)
Look at the summary of this model.
summary(m2)
##
## Call:
## lm(formula = Head ~ Wingcrd + Tarsus + Culmen + Nalospi, data = sparrow)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.37555 -0.29379 0.06689 0.36548 1.50872
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 13.955983 0.469109 29.750 < 2e-16 ***
## Wingcrd 0.062762 0.009058 6.929 7.71e-12 ***
## Tarsus 0.255380 0.026351 9.691 < 2e-16 ***
## Culmen 0.346275 0.032392 10.690 < 2e-16 ***
## Nalospi 0.456229 0.036478 12.507 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.5306 on 974 degrees of freedom
## Multiple R-squared: 0.6946, Adjusted R-squared: 0.6933
## F-statistic: 553.8 on 4 and 974 DF, p-value: < 2.2e-16
Here, we see the common intercept for all the four predictors, as well as their individual slopes (we have no categorical variables in this model, so there are no differences between levels to worry about).
Check the multiple regression page to see how you might go about making a figure of these data.
This is the end. You should now be able to make a wide variety of simple additive and interaction models using continuous and categorical variables.
Please submit the log of this lesson to Google Forms so that Simon may evaluate your progress.
I am not a robot.