\(~~~~~~~~~~~\)Data Wrangling\(~~~~~~~~~~~\)

Asst. Prof. Dr. Somsak Chanaim

International College of Digital Innovation, CMU

June 23, 2026

Warning

“The results from a data frame or tibble are shown as a table using the kable() function from the knitr package.”

The dplyr Package

What is the dplyr package

dplyr is a grammar of data manipulation, providing a consistent set of verbs that help you solve the most common data manipulation challenges:

Five verbs:

  • filter() picks cases based on their values.

  • mutate() adds new variables that are functions of existing variables

  • arrange() changes the ordering of the rows.

  • select() picks variables based on their names.

  • summarise() reduces multiple values down to a single summary.

How to install and use this package

How to use this package

Data frame for learning

The filter() function

The filter() function is used to subset rows in a data frame (or tibble) based on conditions.

It allows you to keep only those rows that meet the specified conditions.

  • filter()returns a data frame or tibble with only the rows that satisfy the condition(s).

  • You can chain filter() with other dplyr functions using the pipe operator |> for more complex data manipulation tasks.

Basic Syntax:

From the data frame Data, we need only group A

The standard code

Use Pipe operator

We need only group A, and the score more than 80

The standard code

Use pipe operator

From the previous code, assign the result to the variable Data2

From Data2, we need the score less than 85

From the previous code, the score not equal 83 too

The mutate() function

The mutate() function is used to create new columns or modify existing ones in a data frame or tibble.

It allows you to perform transformations on your data and add the results as new variables.

Basic Syntax:

Example: From the data frame Data, reducing the score from everyone 20.

if the score are more than or equal 70, your grade is A, else B.

Additional conditions:

score grade
75+ A
71-74 B+
66-70 B
<66 C

case_when() function

case_when() is a super useful function in the dplyr package in R. It’s like a vectorized version of if...else if...else, and is used mainly for conditional transformations inside mutate() or transmute().

Basic Syntax

  • Each condition is followed by ~ and the value to assign if that condition is TRUE.

  • The last condition should usually be TRUE (like an else).

Common mistakes:

  • Don’t forget the TRUE ~ ... for default values.

  • All return values must be of the same type (e.g., all character, or all numeric).

  • case_when() evaluates conditions in order, and stops at the first TRUE.

When to use case_when():

  • Recoding/categorizing variables

  • Creating new columns with conditions

  • Replacing nested ifelse() statements with clearer syntax

The select() function

The select() function is used to choose specific columns from a data frame or tibble.

It allows you to keep only the columns you are interested in, either by naming them directly or using helper functions for more advanced selections.

  • select() allows for both inclusion and exclusion of columns using positive or negative column names.

  • Helper functions like starts_with(), ends_with(), contains(), matches(), and where() can be used within select() for more flexible column selection.

  • The select() function can be used in combination with other dplyr functions using the pipe operator |> for streamlined data manipulation tasks.

Basic Syntax:

Selecting the variable group and grade from the data frame Data

From the Data, I need only group B, and grade more than B, and select the variable group and grade only.

The arrange() function

The arrange() function is used to reorder the rows of a data frame or tibble based on the values of one or more columns.

It can sort the data in ascending or descending order.

  • arrange() orders rows based on the specified columns. The default order is ascending, but you can use desc() to sort in descending order.

  • You can sort by multiple columns by listing them in the order of priority.

  • arrange() can be combined with other dplyr functions using the pipe operator |> for more complex data processing workflows.

Basic Syntax:

1) From the mtcars dataset, I need the variables cyl, gear, mpg, and disp assigned to the object Data3.

2) Sorting Data3 by the variable cyl (from minimum to maximum).

3) Sorting Data3 by the variable cyl (from maximum to minimum).

4) Sorting Data3 by the variables cyl and gear (from minimum to maximum).

The constant vector we should known

Sorting data frame MONTH by month.abb

The unique() function

Used to find the unique values in a categorical variable from a data frame.

The factor variable in R

The factor is a data structure used to represent categorical variables.

Factors are particularly useful when you have data that falls into a limited number of distinct categories, such as gender, blood type, or education level.

Basic Syntax:

  • x is a vector of character

  • levels is the list of unique value in the vector and ordering from left to right.

Levels: Factors store the unique values as levels. If a value is not included in the levels, it will be treated as NA.

Ordered vs. Unordered: Factors can be unordered (nominal) or ordered (ordinal). Ordering affects how comparisons are made between levels.

Factors and Models: Factors are commonly used in statistical modeling because they help R understand the categorical nature of the variable.

Factors are a powerful way to handle categorical data in R, especially when you need to ensure that the data is treated as a categorical variable in analyses or visualizations.

Example

Change variable month in MONTH2, from character to factor.

Based R: The summary() function

Summary Statistics with summary() function

After exploring the built-in summary() function in Base R, which provides quick descriptive statistics for each variable, we can move on to a more flexible and customizable approach using the summarise() function from the dplyr package.

The summarize() function

The summarize() (or summarise()) function is used to create a summary statistic of a data frame or tibble.

It reduces multiple values down to a single value per group, often used in conjunction with the group_by() function.

Basic Syntax:

Grouping: When used withgroup_by(), summarize() can generate summary statistics for each group in your data.

Aggregation: Common summary functions include mean(), sum(), min(), max(), median(), sd(), and n().

Output: The output of summarize() is a data frame or tibble with one row per group (or a single row if not grouped) .

Custom Functions: You can use custom functions within summarize() to create more specific summaries.

Example

1) We need mean, median, SD, VAR from the variable disp.

2) Compute summary statistic based on the variable cyl

3) Compute summary statistic based on the variable on the variables cyl and gear

stat() function in R

  • mean(): The average value of numeric variables.

  • sd(): The standard deviation

  • var(): The variance

  • median(): The median

  • min(): The minimum value from the variable.

  • max(): The maximum value from the variable.

  • quantile(): Find the quantile value at level \(p \in(0,1)\)

  • n(): Count the number of observations in a group or variable (an internal function to use within functions from the dplyr package)

Question

From mtcars dataset,

selecting the cyl = 4 only,

selecting mpg and gear,

create kpg (kilo M. per gallon) (1 mpg (US) = 1.6093 kilometers per gallon (US))

compute (n, mean, quantile 25, 75 amd SD) of kpg separate by gear

Join Data Frame

Join data frame with the function from dplyr package

Join Data Frame funtion

To join data frames using the dplyr package in R, you can use several types of joins depending on how you want to combine the data.

This course we need only 4 ways.

  1. Inner Join: inner_join()

  2. Left Join: left_join()

  3. Right Join: right_join()

  4. Full Join: full_join()

Example

Created two data frames, x and y:

1. Inner Join: inner_join()

Returns rows with matching keys in both data frames.

2. Left Join: left_join()

Returns all rows from the left data frame and the matching rows from the right data frame.

3. Right Join: right_join()

Returns all rows from the right data frame and the matching rows from the left data frame.

4. Full Join: full_join()

Returns all rows when there is a match in either data frame.

Exercise: Part 1

Exercise 1: Using filter()

Filter the rows of the mtcars dataset where the number of cylinders (cyl) is 6 and the miles per gallon (mpg) is greater than 20.

Target output

                mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4      21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag  21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1

Complete the code

mtcars |>
(cyl == 6, )

Exercise 2: Using mutate()

Create a new variable in the mtcars dataset called hp_per_cyl that represents horsepower (hp) per cylinder (cyl).

Target output

                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
Fiat 128            32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic         30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla      33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
Fiat X1-9           27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2       26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
Ferrari Dino        19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
                    hp_per_cyl
Mazda RX4             18.33333
Mazda RX4 Wag         18.33333
Datsun 710            23.25000
Hornet 4 Drive        18.33333
Hornet Sportabout     21.87500
Valiant               17.50000
Duster 360            30.62500
Merc 240D             15.50000
Merc 230              23.75000
Merc 280              20.50000
Merc 280C             20.50000
Merc 450SE            22.50000
Merc 450SL            22.50000
Merc 450SLC           22.50000
Cadillac Fleetwood    25.62500
Lincoln Continental   26.87500
Chrysler Imperial     28.75000
Fiat 128              16.50000
Honda Civic           13.00000
Toyota Corolla        16.25000
Toyota Corona         24.25000
Dodge Challenger      18.75000
AMC Javelin           18.75000
Camaro Z28            30.62500
Pontiac Firebird      21.87500
Fiat X1-9             16.50000
Porsche 914-2         22.75000
Lotus Europa          28.25000
Ford Pantera L        33.00000
Ferrari Dino          29.16667
Maserati Bora         41.87500
Volvo 142E            27.25000

Complete the code

mtcars |>
(hp_per_cyl = )

Exercise 3: Using select()

Select only the columns mpg, hp, and wt from the mtcars dataset.

Target output

                     mpg  hp    wt
Mazda RX4           21.0 110 2.620
Mazda RX4 Wag       21.0 110 2.875
Datsun 710          22.8  93 2.320
Hornet 4 Drive      21.4 110 3.215
Hornet Sportabout   18.7 175 3.440
Valiant             18.1 105 3.460
Duster 360          14.3 245 3.570
Merc 240D           24.4  62 3.190
Merc 230            22.8  95 3.150
Merc 280            19.2 123 3.440
Merc 280C           17.8 123 3.440
Merc 450SE          16.4 180 4.070
Merc 450SL          17.3 180 3.730
Merc 450SLC         15.2 180 3.780
Cadillac Fleetwood  10.4 205 5.250
Lincoln Continental 10.4 215 5.424
Chrysler Imperial   14.7 230 5.345
Fiat 128            32.4  66 2.200
Honda Civic         30.4  52 1.615
Toyota Corolla      33.9  65 1.835
Toyota Corona       21.5  97 2.465
Dodge Challenger    15.5 150 3.520
AMC Javelin         15.2 150 3.435
Camaro Z28          13.3 245 3.840
Pontiac Firebird    19.2 175 3.845
Fiat X1-9           27.3  66 1.935
Porsche 914-2       26.0  91 2.140
Lotus Europa        30.4 113 1.513
Ford Pantera L      15.8 264 3.170
Ferrari Dino        19.7 175 2.770
Maserati Bora       15.0 335 3.570
Volvo 142E          21.4 109 2.780

Complete the code

mtcars |>
()

Exercise 4: Using arrange()

Arrange the mtcars dataset in ascending order of mpg and then by descending order of hp.

Target output

                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
Ferrari Dino        19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Porsche 914-2       26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Fiat X1-9           27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Honda Civic         30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Fiat 128            32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Toyota Corolla      33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1

Complete the code

mtcars |>
(, )

Exercise 5: Using summarize()

Calculate the mean horsepower (hp) for each number of cylinders (cyl) in the mtcars dataset.

Target output

# A tibble: 3 × 2
    cyl mean_hp
  <dbl>   <dbl>
1     4    82.6
2     6   122. 
3     8   209. 

Complete the code

mtcars |>
(cyl) |>
( = )

Exercise: Part 2

Exercise 6: Combining filter() and mutate()

Filter the mtcars dataset for cars with more than 4 gears, then create a variable mpg_per_wt that represents miles per gallon per unit of weight.

Target output

                mpg cyl  disp  hp drat    wt qsec vs am gear carb mpg_per_wt
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.7  0  1    5    2  12.149533
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.9  1  1    5    2  20.092531
Ford Pantera L 15.8   8 351.0 264 4.22 3.170 14.5  0  1    5    4   4.984227
Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.5  0  1    5    6   7.111913
Maserati Bora  15.0   8 301.0 335 3.54 3.570 14.6  0  1    5    8   4.201681

Complete the code

mtcars |>
filter() |>
( = )

Exercise 7: Combining select() and arrange()

Select the mpg, hp, and wt columns from the mtcars dataset and then arrange the resulting data in descending order of wt.

Target output

                     mpg  hp    wt
Lincoln Continental 10.4 215 5.424
Chrysler Imperial   14.7 230 5.345
Cadillac Fleetwood  10.4 205 5.250
Merc 450SE          16.4 180 4.070
Pontiac Firebird    19.2 175 3.845
Camaro Z28          13.3 245 3.840
Merc 450SLC         15.2 180 3.780
Merc 450SL          17.3 180 3.730
Duster 360          14.3 245 3.570
Maserati Bora       15.0 335 3.570
Dodge Challenger    15.5 150 3.520
Valiant             18.1 105 3.460
Hornet Sportabout   18.7 175 3.440
Merc 280            19.2 123 3.440
Merc 280C           17.8 123 3.440
AMC Javelin         15.2 150 3.435
Hornet 4 Drive      21.4 110 3.215
Merc 240D           24.4  62 3.190
Ford Pantera L      15.8 264 3.170
Merc 230            22.8  95 3.150
Mazda RX4 Wag       21.0 110 2.875
Volvo 142E          21.4 109 2.780
Ferrari Dino        19.7 175 2.770
Mazda RX4           21.0 110 2.620
Toyota Corona       21.5  97 2.465
Datsun 710          22.8  93 2.320
Fiat 128            32.4  66 2.200
Porsche 914-2       26.0  91 2.140
Fiat X1-9           27.3  66 1.935
Toyota Corolla      33.9  65 1.835
Honda Civic         30.4  52 1.615
Lotus Europa        30.4 113 1.513

Complete the code

mtcars |>
select() |>
()

Exercise 8: Combining filter(), mutate(), and summarize()

Filter the mtcars dataset for cars with more than 100 horsepower, create a variable hp_per_mpg as the ratio of horsepower to miles per gallon, and then calculate the average hp_per_mpg for each number of cylinders.

Target output

# A tibble: 3 × 2
    cyl avg_hp_per_mpg
  <dbl>          <dbl>
1     4           4.41
2     6           6.23
3     8          14.4 

Complete the code

mtcars |>
filter() |>
mutate(hp_per_mpg = ) |>
group_by() |>
summarize( = )

Exercise 9: Using mutate() with conditional logic

Create a variable in the mtcars dataset called performance that categorizes cars as ‘High’ if horsepower (hp) is above 150, and ‘Low’ otherwise. (Note: Text values must be wrapped in quotes!)

Target output

                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
Fiat 128            32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic         30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla      33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
Fiat X1-9           27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2       26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
Ferrari Dino        19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
                    performance
Mazda RX4                   Low
Mazda RX4 Wag               Low
Datsun 710                  Low
Hornet 4 Drive              Low
Hornet Sportabout          High
Valiant                     Low
Duster 360                 High
Merc 240D                   Low
Merc 230                    Low
Merc 280                    Low
Merc 280C                   Low
Merc 450SE                 High
Merc 450SL                 High
Merc 450SLC                High
Cadillac Fleetwood         High
Lincoln Continental        High
Chrysler Imperial          High
Fiat 128                    Low
Honda Civic                 Low
Toyota Corolla              Low
Toyota Corona               Low
Dodge Challenger            Low
AMC Javelin                 Low
Camaro Z28                 High
Pontiac Firebird           High
Fiat X1-9                   Low
Porsche 914-2               Low
Lotus Europa                Low
Ford Pantera L             High
Ferrari Dino               High
Maserati Bora              High
Volvo 142E                  Low

Complete the code

mtcars |>
(performance = (, "High", ))

Exercise 10: Combining All Functions

Filter cars with cyl > 4, select necessary columns, create and sort by efficiency (mpg / wt), and then calculate the average efficiency for each number of gears.

Target output

# A tibble: 3 × 2
   gear avg_efficiency
  <dbl>          <dbl>
1     3           4.14
2     4           6.52
3     5           5.43

Complete the code

mtcars |>
filter() |>
select(mpg, hp, wt, gear) |>
mutate(efficiency = ) |>
arrange() |>
group_by() |>
summarize( = )

Exercise: Part 3

Exercise 11: Analyze Fuel Efficiency

Filter for cyl > 4 and am == 1, calculate efficiency_ratio, select specific columns, arrange by efficiency_ratio in descending order, and find the average for each cylinder group.

Target output

# A tibble: 2 × 2
    cyl avg_efficiency
  <dbl>          <dbl>
1     6           7.48
2     8           4.59

Complete the code

result <- mtcars |>
filter() |>
mutate(efficiency_ratio = ) |>
select(cyl, mpg, wt, efficiency_ratio) |>
(desc(efficiency_ratio)) |>
group_by(cyl) |>
summarize(avg_efficiency = )

Exercise 12: Performance Analysis

Filter for cyl > 6, calculate performance_index (hp * qsec), select columns, arrange by performance_index in ascending order, and calculate the median performance_index for each cylinder group.

Target output

# A tibble: 1 × 2
    cyl median_performance
  <dbl>              <dbl>
1     8              3463.

Complete the code

result <- mtcars |>
filter(cyl > 6) |>
mutate(performance_index = ) |>
select(cyl, hp, qsec, performance_index) |>
(performance_index) |>
group_by(cyl) |>
summarize(median_performance = )

Exercise 13: Cost Efficiency

Filter for mpg > 20, calculate cost_efficiency (hp / mpg), select columns, arrange by cost_efficiency in descending order, and find the maximum cost_efficiency for each gear group.

Target output

# A tibble: 3 × 2
   gear max_cost_efficiency
  <dbl>               <dbl>
1     3                5.14
2     4                5.24
3     5                3.72

Complete the code

result <- mtcars |>
filter() |>
mutate(cost_efficiency = ) |>
select(mpg, hp, wt, cost_efficiency, gear) |>
(desc(cost_efficiency)) |>
group_by(gear) |>
summarize(max_cost_efficiency = )

Exercise 14: Weight-to-Power Ratio

Filter for wt > 3, calculate weight_to_power (wt / hp), select columns, arrange by weight_to_power in ascending order, and calculate the average weight_to_power for each gear group.

Target output

# A tibble: 3 × 2
   gear avg_weight_to_power
  <dbl>               <dbl>
1     3              0.0228
2     4              0.0351
3     5              0.0113

Complete the code

result <- mtcars |>
filter() |>
mutate(weight_to_power = ) |>
select(wt, hp, weight_to_power, gear) |>
(weight_to_power) |>
group_by(gear) |>
summarize(avg_weight_to_power = )

Exercise 15: Power Efficiency by Cylinder

Filter for cars with 4 or 6 cylinders, calculate power_efficiency (hp / mpg), select columns, arrange by power_efficiency in descending order, and calculate the average for each cylinder group.

Target output

# A tibble: 2 × 2
    cyl avg_power_efficiency
  <dbl>                <dbl>
1     4                 3.24
2     6                 6.23

Complete the code

result <- mtcars |>
filter(cyl ) |>
mutate(power_efficiency = ) |>
select(cyl, hp, mpg, power_efficiency) |>
(desc(power_efficiency)) |>
group_by(cyl) |>
summarize(avg_power_efficiency = )

Exercise: Part 4

Exercise 16: Using left_join()

Join car_specs (left) with car_prices (right) by ‘car_model’ keeping all rows from the left table.

Target output

  car_model  hp price
1 Mazda RX4 110  2000
2     Civic  93  1500
3   Corolla  65    NA

Complete the code

car_specs <- data.frame(car_model = c("Mazda RX4", "Civic", "Corolla"), hp = c(110, 93, 65))
car_prices <- data.frame(car_model = c("Mazda RX4", "Civic", "Mustang"), price = c(2000, 1500, 5000))

car_specs |>
(car_prices, by = )

Exercise 17: Using right_join()

Join car_specs with car_prices by ‘car_model’ keeping all rows from the right table (car_prices).

Target output

  car_model  hp price
1 Mazda RX4 110  2000
2     Civic  93  1500
3   Mustang  NA  5000

Complete the code

car_specs <- data.frame(car_model = c("Mazda RX4", "Civic", "Corolla"), hp = c(110, 93, 65))
car_prices <- data.frame(car_model = c("Mazda RX4", "Civic", "Mustang"), price = c(2000, 1500, 5000))

car_specs |>
(car_prices, by = )

Exercise 18: Using inner_join()

Join car_specs with car_prices by ‘car_model’ keeping only rows that match in BOTH data frames.

Target output

  car_model  hp price
1 Mazda RX4 110  2000
2     Civic  93  1500

Complete the code

car_specs <- data.frame(car_model = c("Mazda RX4", "Civic", "Corolla"), hp = c(110, 93, 65))
car_prices <- data.frame(car_model = c("Mazda RX4", "Civic", "Mustang"), price = c(2000, 1500, 5000))

car_specs |>
(car_prices, by = )

Exercise 19: Using full_join()

Perform an outer join by combining all rows from both car_specs and car_prices using full_join().

Target output

  car_model  hp price
1 Mazda RX4 110  2000
2     Civic  93  1500
3   Corolla  65    NA
4   Mustang  NA  5000

Complete the code

car_specs <- data.frame(car_model = c("Mazda RX4", "Civic", "Corolla"), hp = c(110, 93, 65))
car_prices <- data.frame(car_model = c("Mazda RX4", "Civic", "Mustang"), price = c(2000, 1500, 5000))

car_specs |>
(car_prices, by = )

Exercise 20: Advanced Join with Filtering

Left join car_specs with car_prices by ‘car_model’, then use filter() to keep rows where price > 1800.

Target output

  car_model  hp price
1 Mazda RX4 110  2000

Complete the code

car_specs <- data.frame(car_model = c("Mazda RX4", "Civic", "Corolla"), hp = c(110, 93, 65))
car_prices <- data.frame(car_model = c("Mazda RX4", "Civic", "Mustang"), price = c(2000, 1500, 5000))

car_specs |>
left_join(car_prices, by = ) |>
()

Thank you

All animations are from gadenbuie