# Score Table
scores <- data.frame(
Student ID = c("S001", "S002", "S003", "S005"),
Score = c(88, 92, 76, 80),
stringsAsFactors = FALSE
)
print("Students table:")
print(students)
print("ScoreQ-table:")
print(scores)
# Inner join (only keep students that exist in both tables)
inner_join <- merge(students, scores, by = "Student ID")
print("Inner join:")
print(inner_join)
# Left join (keep all students, fill NA for those without scores)
left_join <- merge(students, scores, by = "Student ID", all.x = TRUE)
print("Left Join:")
print(left_join)
Executing the above code outputs the following results:
"Students table:"
Student ID Name
1 S001 Zhang San
2 S002 Li Si
3 S003 Wang Wu
4 S004 Zhao Liu
"ScoreQ-table:"
Student ID Score
1 S001 88
2 S002 92
3 S003 76
4 S005 80
"Inner join:"
Student ID Name Score
1 S001 Zhang San 88
2 S002 Li Si 92
3 S003 Wang Wu 76
"Left Join:"
Student ID Name Score
1 S001 Zhang San 88
2 S002 Li Si 92
3 S003 Wang Wu 76
4 S004 Zhao Liu NA
R Language Examples