# Introduction

This document demonstrates how to conduct a simple linear regression using the `mtcars` dataset in R. We will explore data frames, use the `$` operator to access data, summarize variables, visualize relationships, and fit a linear regression model.

# Loading the Data

We will begin by loading the `mtcars` dataset, a built-in dataset in R that contains information about various car attributes.

```{r}
# Load the mtcars dataset
data(mtcars)
```

# Understanding Data Frames

A data frame in R is similar to a table in a spreadsheet, where each row represents an observation (in this case, a car model) and each column represents a variable (such as horsepower or miles per gallon).

```{r}
# Display the first few rows of the mtcars dataset
head(mtcars)
```

# Understanding the `$` Operator in R

The `$` operator allows us to access specific columns within the data frame. For example, we can use it to extract the `mpg` (miles per gallon) column.

```{r}
# Access the mpg column in the mtcars dataset
mtcars$mpg
```

# Summarizing the Miles Per Gallon Variable

Next, we use the `summary()` function to generate summary statistics for the `mpg` variable. This gives us a quick overview of the central tendency and spread of the data.

```{r}
# Summarize the mpg variable
mpg_summary <- summary(mtcars$mpg)
mpg_summary
```

# Plotting Miles Per Gallon vs. Horsepower

We can explore the relationship between miles per gallon (mpg) and horsepower (hp) by creating a scatter plot. This visualization helps us to see if there's any apparent relationship between the two variables.

```{r}
# Create a scatter plot of mpg vs. hp
plot(x = mtcars$hp, 
     y = mtcars$mpg, 
     xlab = "Horsepower", 
     ylab = "Miles per Gallon", 
     main = "Miles per Gallon vs Horsepower")
```

# Fitting a Trend Line

To quantify the relationship between `mpg` and `hp`, we fit a linear regression model using the `lm()` function. We then add the fitted regression line to our scatter plot.

```{r}
# Fit a linear model predicting mpg based on hp
fit <- lm(mpg ~ hp, data = mtcars)

# Create the scatter plot again and add the regression line
plot(x = mtcars$hp, 
     y = mtcars$mpg, 
     xlab = "Horsepower", 
     ylab = "Miles per Gallon", 
     main = "Miles per Gallon vs Horsepower")
abline(fit, col="red")
```

# Conclusion

The analysis shows a negative relationship between horsepower and miles per gallon, meaning that as horsepower increases, fuel efficiency decreases. This relationship is quantified by the linear regression model and is visually represented by the trend line on the scatter plot.

