Exercise 1 Filtering and Summarizing Fuel Efficiency
Exercise 1 Filtering and Summarizing Fuel Efficiency
Each
exercise explores key R skills, with solutions to support learning.
## Introduction
The `mtcars` dataset, built into R, includes data on 32 cars from 1974, with variables like `mpg`
(miles per gallon), `wt` (weight in 1000 lbs), `hp` (horsepower), `cyl` (cylinders), and `am` (trans-
mission: 0 = automatic, 1 = manual). These exercises cover filtering, summarizing, correlation, re-
gression, and visualization with `dplyr` and base R. Each task fills approximately one page.
**Setup**:
```R
library(dplyr)
data(mtcars)
```
**Solution**:
```R
efficient_cars <- mtcars %>%
filter(mpg > 22) %>%
group_by(cyl) %>%
summarise(avg_wt = mean(wt, na.rm = TRUE), median_hp = median(hp, na.rm = TRUE), count =
n())
print(efficient_cars)
```
**Output**:
```
# A tibble: 2 × 4
cyl avg_wt median_hp count
<dbl> <dbl> <dbl> <int>
1 4 2.24 82 8
2 6 2.46 110 3
```
**Explanation**: Only 4- and 6-cylinder cars have `mpg` > 22. Four-cylinder cars are lighter
(avg_wt ≈ 2.24) and less powerful (median_hp = 82) than 6-cylinder cars (avg_wt ≈ 2.46, medi-
an_hp = 110). Most efficient cars (8/11) have 4 cylinders, suggesting smaller engines boost effici-
ency. Lowering to `mpg` > 18 includes heavier 8-cylinder cars (avg_wt ≈ 3.5), showing trade-offs.
Try filtering `hp` to refine insights.