Simple regression
Regression analysis with R is easy once you have your data in a neat data frame. You can simply use the lm()
function to fit a linear model. The first argument of lm()
is a formula
, which defines the target variable and the explanatory variable(s).
The formula should be y ~ x
, where y
is the target variable and x
the explanatory variable. The second argument of lm()
is data
, which should be a data frame where y
and x
are columns.
The output of lm()
is a linear model object, which can be saved for later use. The generic function summary()
can be used to print out a summary of the model.
This exercise is part of the course
Helsinki Open Data Science
Exercise instructions
- Create a scatter plot of 'points' versus 'attitude'.
- Fit a regression model where 'points' is the target and 'attitude' is the explanatory variable
- Print out the summary of the linear model object
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# learning2014 is available
# a scatter plot of points versus attitude
library(ggplot2)
qplot(attitude, points, data = learning2014) + geom_smooth(method = "lm")
# fit a linear model
my_model <- lm(points ~ 1, data = learning2014)
# print out a summary of the model