rm(list = ls()) #remove ~ everything in the working environment myX<-1:10 myY<-jitter(1:10) adjust<-lm(myY ~ myX) # Use adjust<-lm(myY ~ 0 + myX) to force the intercept at 0 plot(myX,myY,abline(adjust))
The first line is to clear the working environment (e.g. delete variables) and I recommend to use it everytime you start a new script. The next two lines are used to generate 2 vectors (myX and myY). Note that I use
<- and not
= to assign a value to a variable (= works nicely here but it is best not to use it. See here for some explanations). myX is a vector containing 10 integer values (from 1 to 10), myY is myX with some noise (using the function jitter). We can have a look at these two vectors just by typing their names.
##  1 2 3 4 5 6 7 8 9 10
Because jitter add random values, you will produce different numbers everytime you run this function. The function lm (linear model) is used for fitting. The result is passed into a new variable (here adjust but I could use any other names) and then (line 5), we make a simple plot (myY versus myX plus the result of the fit). Note that I use the function abline, which adds a simple line to any existing plot.
##  0.9119364 1.8619898 2.8056814 4.1016091 4.8022902 5.8452231 7.1772783 7.9499693 ##  9.1782965 9.9774281
It is easy to get the estimated parameters for the Slope (0.9843) and the Intercept (0.1337). Just type:
## ## Call: ## lm(formula = myY ~ myX) ## ## Coefficients: ## (Intercept) myX ## -0.1653 1.0230
The Coefficient of determination (which can be used to asses the goodness of fit for a linear model) is:
## $r.squared ##  0.9983183