2024-02-17

Simple Linear Regression

Definition and examples.

Definition

Simple Linear Regression models the relationship between a dependent variable and a single independent variable.

Mathematical Representation

The linear regression equation is given by:

\[ Y = \beta_0 + \beta_1 X + \varepsilon \]

Linear Equation

The general form of a linear equation is given by:

\[ y = mx + b \]

where: - \(y\) is the dependent variable, - \(x\) is the independent variable, - \(m\) is the slope of the line, and - \(b\) is the y-intercept.

This equation represents a straight line on a Cartesian plane, with the slope \(m\) determining the steepness of the line, and the y-intercept \(b\) indicating the point where the line crosses the y-axis.

Example

Consider a dataset of hours studied (\(X\)) and exam scores (\(Y\)).

Scatter Plot

R Code for Scatter Plot

# R code for creating a scatter plot

library(ggplot2)

# Generate random data for illustration
hours_studied <- c(1, 2, 3, 4, 5)
exam_scores <- c(50, 60, 70, 80, 90)

your_data <- data.frame(hours_studied, exam_scores)

# Create ggplot with the data frame
scatter_plot <- ggplot(your_data, aes(x = hours_studied, y = exam_scores)) +
  geom_point() +
  labs(title = "Scatter Plot of Hours Studied vs Exam Scores")

# Print the ggplot object
print(scatter_plot)

Regression Line

## `geom_smooth()` using formula = 'y ~ x'

3D Plot

## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
## Warning: Specifying width/height in layout() is now deprecated.
## Please specify in ggplotly() or plot_ly()
## No scatter3d mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
## Warning: `includeHTML()` was provided a `path` that appears to be a complete HTML document.
## ✖ Path: /var/folders/t0/167xpp3d2xndcjk_7gqx83hw0000gp/T//RtmpAWWDjj/filee6732a0838b.html
## ℹ Use `tags$iframe()` to include an HTML document. You can either ensure `path` is accessible in your app or document (see e.g. `shiny::addResourcePath()`) and pass the relative path to the `src` argument. Or you can read the contents of `path` and pass the contents to `srcdoc`.
plotly

Conclusion

In conclusion, our exploration of simple linear regression using R and Plotly shows us the capabilities of such a program to analyze data in different ways.