0% found this document useful (0 votes)
12 views1 page

Exercise 1 Filtering and Summarizing Fuel Efficiency

First R exercise

Uploaded by

buchleser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views1 page

Exercise 1 Filtering and Summarizing Fuel Efficiency

First R exercise

Uploaded by

buchleser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

This document provides detailed exercises for data analysis in R using the `mtcars` dataset.

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)
```

## Exercise 1: Filtering and Summarizing Fuel Efficiency


**Objective**: Filter and group data to analyze fuel-efficient cars.
**Description**: Fuel efficiency (`mpg`) varies by cylinders (`cyl`). Identify high-efficiency cars
and summarize their traits.
**Tasks**:
1. Filter `mtcars` for `mpg` > 22.
2. Group by `cyl` and compute average `wt`, median `hp`, and count.
3. Interpret: What does this suggest about efficient cars?
4. Explore: Try `mpg` > 18 and compare.
**Expected Output**: Table with `cyl`, `avg_wt`, `median_hp`, `count`. Interpretation paragraph.
**Hint**: Use `filter()`, `group_by()`, `summarise()`. Use `na.rm = TRUE`.
**Space for Notes**: Test other filters (e.g., `hp` < 100).

**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.

You might also like