Lab 02: Linear Regression
Saptarshi Chakraborty
2023-01-29
Libraries
The
library()
function is used to load
libraries
, or groups of functions and data sets that are not included
in the base
R
distribution.
Basic functions that perform least squares linear regression and other simple
analyses come standard with the base distribution, but more exotic functions require additional libraries.
Here we load the
MASS
package, which is a very large collection of data sets and functions. We also load the
ISLR2
package, which includes the data sets associated with this book.
library(MASS)
library(ISLR2)
##
## Attaching package: 'ISLR2'
## The following object is masked from 'package:MASS':
##
##
Boston
If you receive an error message when loading any of these libraries, it likely indicates that the corresponding
library has not yet been installed on your system.
Some libraries, such as
MASS
, come with
R
and do
not need to be separately installed on your computer.
However, other packages, such as
ISLR2
, must
be downloaded the first time they are used.
This can be done directly from within
R
. For example, on
a Windows system, select the
Install package
option under the
Packages
tab.
After you select any
mirror site, a list of available packages will appear.
Simply select the package you wish to install and
R
will automatically download the package.
Alternatively, this can be done at the
R
command line via
install.packages("ISLR2")
.
This installation only needs to be done the first time you use a package.
However, the
library()
function must be called within each
R
session.
Simple Linear Regression
The
ISLR2
library contains the
Boston
data set, which records
medv
(median house value) for
506
census
tracts in Boston. We will seek to predict
medv
using
12
predictors such as
rmvar
(average number of rooms
per house),
age
(average age of houses), and
lstat
(percent of households with low socioeconomic status).
head(Boston)
##
crim zn indus chas
nox
rm
age
dis rad tax ptratio lstat medv
## 1 0.00632 18
2.31
0 0.538 6.575 65.2 4.0900
1 296
15.3
4.98 24.0
## 2 0.02731
0
7.07
0 0.469 6.421 78.9 4.9671
2 242
17.8
9.14 21.6
1