---
title: 'R for Researchers: Regression (OLS) solutions'
date: "April 2015"
---
This article contains solutions to exercises for an article in the
series R for Researchers.
For a list of topics covered by this series, see the
[Introduction](RFR_Introduction.html) article.
If you\'re new to R we highly recommend reading the articles in order.
There is often more than one approach to the exercises.
Do not be concerned if your approach is different than
the solution provided.
These solutions require the solutions from the prior lesson be
run in your R session.
```{r, echo=FALSE, results="hide", message=FALSE, warning=FALSE, fig.show='hide'}
source("Scripts/RFR_alfalfa_DP.R")
source("Scripts/RFR_alfalfa_DE.R")
```
#### Exercise solutions
These exercises use the alfalfa dataset and the work
you started on the alfAnalysis script.
Open the script and run all the commands in the script
to prepare your session for these problems.
Note, we will use the shade and irrig variable as continuous
variables for these exercise.
They could also be considered as factor variables.
Since both represent increasing levels we first try to
use them as scale.
1. Set the the reference level of the inoc variable to cntrl.
```{r, comment=NA }
#######################################################
#######################################################
##
## Regression
##
#######################################################
#######################################################
str(alfalfa$inoc)
alfalfa$inoc <- factor(alfalfa$inoc,levels=c("cntrl","A","B","C","D") )
```
2. Create a quadratic poly term for the shade
variable.
```{r, comment=NA }
shade2 <- poly(alfalfa$shade, degree=2)
```
3. Regress yield on the irrig, inoc, the quadratic shade term,
and all their interactions.
```{r, comment=NA }
out <- lm(yield~(irrig+inoc+shade2)^2, data=alfalfa)
summary(out)
```
4. Use the backward selection method to reduce the model.
Use the significance of the term as the criteria,
as was done in the lesson.
There are two methods provided in this solution.
```{r, comment=NA }
step(out, test="F")
out2 <- lm(yield~irrig+inoc+shade2+irrig:inoc+irrig:shade2,
data=alfalfa)
drop1(out2, test="F")
out3 <- lm(yield~irrig+inoc+shade2+irrig:inoc, data=alfalfa)
drop1(out3, test="F")
out4 <- lm(yield~irrig+inoc+shade2, data=alfalfa)
drop1(out4, test="F")
out5 <- lm(yield~irrig+inoc+shade, data=alfalfa)
drop1(out5, test="F")
```
5. Commit your changes to AlfAnalysis.
There is no code associated with the solution to this problem.
Return to the [Regression (OLS)](RFR_Regression.html) article.
Last Revised: 3/2/2015