library(dplyr)
students <- data.frame(
student_id = 101:104,
student_name = c("Ava", "Ben", "Cora", "Diego"),
major_code = c("DANL", "BIOL", "DANL", "ART")
)
majors <- data.frame(
major_code = c("BIOL", "DANL", "ECON"),
major_name = c("Biology", "Data Analytics", "Economics")
)Classwork 9
Combining Tables with left_join()
Data
Analytics
On this page
Complete the questions and submit your responses on the corresponding Brightspace page. Fill in every ____. Copy the completed R code into your script and run it after the setup below.
These two small tables contain fictional student and major information. We want to keep every student and add the full name of each student’s major when a matching code exists.
students
| student_id | student_name | major_code |
|---|---|---|
| 101 | Ava | DANL |
| 102 | Ben | BIOL |
| 103 | Cora | DANL |
| 104 | Diego | ART |
majors
| major_code | major_name |
|---|---|
| BIOL | Biology |
| DANL | Data Analytics |
| ECON | Economics |
The rows appear in different orders. A join matches key values, not row positions.
Question 1
Which table is the main (left) table, which table supplies the major names, and which column is the matching key? Fill in the names below.
- Main (left) table:
____ - Lookup table supplying the major names:
____ - Matching key column:
____
- Main (left) table:
students, because we want to keep every student. - Lookup table:
majors, which supplies the full major names. - Matching key column:
major_code, which appears in both tables.
The join matches equal major_code values, so the tables can have different row orders. Ava and Cora both have DANL and can use the same matching row in majors.
Question 2
Fill in the code to add major_name to the student table. Save the result as students_with_major and display it.
students_with_major <- ____ |>
____(____, by = "____")
students_with_majorStart with students on the left, use left_join() to add information from majors, and specify the matching column with by = "major_code".
students_with_major <- students |>
left_join(majors, by = "major_code")
students_with_major student_id student_name major_code major_name
1 101 Ava DANL Data Analytics
2 102 Ben BIOL Biology
3 103 Cora DANL Data Analytics
4 104 Diego ART <NA>
Ava and Cora receive Data Analytics, and Ben receives Biology. Diego remains in the result, with NA for major_name, because his ART code has no match in majors. The ECON lookup row has no matching student and does not appear in the result. Here, each code occurs only once in majors, so the joined table has the same four rows as students.