--- title: "Linear regression with RMarkdown" author: "Laurent DELSOL" date: '`r format(Sys.time(), "%d %B %Y")`' output: ioslides_presentation: code_folding: hide toc: yes slidy_presentation: default beamer_presentation: default params: dataset: trees x: Girth y: Volume z: Height --- ```{r setup, include=FALSE} require(plot_ly) require(plot3D) getOutputFormat <- function() { output <- rmarkdown:::parse_yaml_front_matter( readLines(knitr::current_input()) )$output if (is.list(output)){ return(names(output)[1]) } else { return(output[1]) } } knitr::opts_chunk$set(echo = FALSE, warning=FALSE, message=FALSE) D=params$dataset X=params$x Y=params$y Z=params$z if (!is.null(eval(parse(text=D))) & charmatch(D,ls('package:datasets'),nomatch=FALSE)) { eval(parse(text=paste("data(",D,")",sep=""))) attach(eval(parse(text=D))) } x=eval(parse(text=X)) y=eval(parse(text=Y)) z=eval(parse(text=Z)) ``` ## Motivating example (dataset **`r params$dataset`**) : How does **`r params$y`** depend on **`r params$x`**? $$`r params$y`\stackrel{?}=a_0\times `r params$x`+b_0+\epsilon$$ ```{r Motiv, fig.height=4} Format=getOutputFormat() if (Format=='ioslides_presentation' | Format=='slidy_presentation') { library(plotly) if (!is.null(eval(parse(text=D))) & charmatch(D,ls('package:datasets'),nomatch=FALSE)) { plot_ly(eval(parse(text=D)),x=eval(parse(text=paste("~",X,sep=''))),y=eval(parse(text=paste("~",Y,sep=''))),type='scatter',mode='markers') } else {plot_ly(x=~x,y=~y,type='scatter',mode='markers')} } if (getOutputFormat()=='beamer_presentation') { plot(x,y,xlab=X,ylab=Y) } ``` ## Problem formulation + Regression problem : **$Y=f(X)+\epsilon$** + **$Y$** response variable + **$X$** explanatory variable + **$f$** unknown link function + **$\epsilon$** error term + Does **$Y$** depend on **$X$**? What kind of link is it? How to estimate the function **$f$**? + Simplest case: Linear regression $$Y=a_0\times X+b_0+\epsilon$$ ## A. Scatter plot + Does **$Y$** depend on **$X$**? + How intense is the link? + Is the potential link linear? ```{r Scatter Plot, fig.height=3} x0=runif(100) y1=runif(100) e=rnorm(100,0,.2) y2=cos(2*pi*x0)+e y3=2*x0+e y4=-x0+e/5 par(mfrow=c(1,4)) plot(x0,y1,xlab='X',ylab='Y') plot(x0,y2,xlab='X',ylab='Y') plot(x0,y3,xlab='X',ylab='Y') plot(x0,y4,xlab='X',ylab='Y') par(mfrow=c(1,1)) ``` ## B. Correlation coefficient $$\rho(X,Y)=\frac{cov(X,Y)}{\sqrt{S^2_X S^2_Y}} (\approx `r cor(x,y)` \text{ in our example})$$ ### Properties + $-1\leq \rho(X,Y)\leq 1$ + $|\rho(X,Y)|=1\ \Leftrightarrow \exists a,b\in\mathbb{R},\, \forall i\in\{1,\dots,n\},\, y_i=ax_i+b$ + Hence a strong linear link gives $|\rho(X,Y)|$ close to 1. + The sign of $\rho(X,Y)$ is related to the way $Y$ and $X$ tend to evolve jointly (positively or negatively). ## Regression line estimation $$\small{Y=\color{blue}{a_0X+b_0}+\color{red}{\epsilon_{(a_0,b_0)}}}$$ We look for $(\hat a_0,\hat b_0)$ minimizing the following least squares criterion: $\small{MC(a,b)=\sum_{i=1}^n\left(y_i-\color{blue}{(ax_i+b)}\right)^2=\sum_{i=1}^n\left(\color{red}{\epsilon_{i,(a,b)}}\right)^2}$ ```{r Min, fig.height=4} res=lm(y~x) a0=res$coefficients[2] b0=res$coefficients[1] plot(x,y,xlab=X,ylab=Y,ylim=c(min(y,min(a0*x+b0)),max(y,max(a0*x+b0)))) lines(x,a0*x+b0,xlab=X,ylab=Y,col='blue') lines(x,a0*x+b0,xlab=X,ylab=Y,col='blue',type='p',pch=20) segments(x,a0*x+b0,x,y,col='red') ``` ## Regression line estimation >- $\hat a_0=\frac{cov(X,Y)}{S^2_X}=\rho(X,Y)\frac{S_Y}{S_X}(\approx `r signif(a0,3)`\text{ in our example})$ >- $\hat b_0=\overline Y-\hat a_0\overline X (\approx `r signif(b0,3)`\text{ in our example})$ >- Modelling quality : coefficient of determination $$\small{R^2\left(X,Y\right)=\frac{\sum_{i=1}^n(\hat a_0X_i+\hat b_0-\overline{\hat a_0X+\hat b_0})^2}{\sum_{i=1}^n(Y_i-\overline{Y})^2}=\left(\rho(X,Y)\right)^2}$$ In our example: $R^2\left(X,Y\right)\approx`r (cor(x,y))^2`$ >- Estimation of the mean value of `r params$y` when `r params$x`=`r signif(median(x),3)` $$\hat{`r params$y`}=`r a0`\times`r signif(median(x),3)`+`r b0`\approx `r a0*signif(median(x),3)+b0`$$ ## Adding a third variable? ```{r} library(plot3D) if (Format!='beamer_presentation') { if (!is.null(eval(parse(text=D))) & charmatch(D,ls('package:datasets'),nomatch=FALSE)) { plot_ly(eval(parse(text=D)),x=eval(parse(text=paste("~",X,sep=''))),y=eval(parse(text=paste("~",Z,sep=''))),z=eval(parse(text=paste("~",Y,sep='')))) } else {plot_ly(x=~x,y=~z,z=~y)} } if (Format=='beamer_presentation') { scatter3D(x,z,y,xlab=X,ylab=Z,zlab=Y) } ```