Name: [Tanaia Way]
Course: [DAAN 703]

Use the companion lab for complete instructions. Replace bracketed prompts. Enable each solution chunk after completing it. Include predictions before execution. Do not use the instructor key as your submission.

roster <- tibble(
  learner_id = sprintf("L%02d", 1:8),
  pathway = rep(c("DASC 240", "DAAN 703"), each = 4)
)
submissions <- tibble(
  learner_id = c("L06", "L01", "L09", "L03", "L05", "L02"),
  project = "joins",
  score = c(8, 8, 10, NA_real_, 9, 7)
)
roster
submissions

Reading R1

Two tables can have the same number of rows with a different order. Combining them by position could match data from one state to another so it’s safer to join the tables using a common key. For example, using the state name to make sure the information matches.

Reading R2

Using left join keeps everyone in the roster even when they don’t have a matching record in the other table. On the other hand, an anti join identifies roster members who do not match. S

Semi join keeps roster members who have a match but it does not add columns from the other table. An inner join keeps matching records and includes information from both tables.

Reading R3

Before column binding, both tables have to have the same number of rows and each has to represent the same observation in the same order. Row binding combines tables by stacking their rows. If one table is missing a column that exists in the other, bind_rows() will fill the missing values as long as they’re compatible.

Reading R4

Set operations compares entire rows instead of selected keys only. It examines all the column values to determine whether rows are duplicated. These rows are treated as one row therefore, repeated copies are removed. This is why operations may not be useful when we need to keep track of repeated records.

Reading R5

In merge(), a left join uses all.x = TRUE, while a right join uses all.y = TRUE. A full join uses all = TRUE. An inner join uses the default settings - both all.x and all.y are FALSE. When we convert the inputs to data.table, it makes sure we are working with the correct data structure and can use the features and performance benefits of the data.table package.

Reading R6

In baseball data, plyerID alone may not be enough due to a player having salary records for multiple years. If we use PlayerID only, it could match information from different season incorrectly. Using a combination of PlayerID and YearID is usually needed, and team information could be necessary. For the CO2 exercise, the key of the yearly summary is ‘year’ because each year has one summarized value.

U1

The roster contains enrolled learners, while the submissions table contains project records. I would use a left join because I want to keep every enrolled learner, including those who do not have a matching submission record. I expect a one-to-one relationship with each learner should have one submission record for this project.

If learners submitted multiple projects, the submissions table would have a different grain. Each row would represent one learner-project combination, and the key would likely be learner_id and project. The relationship would become one-to-many if joining all projects to a learner-level roster.

U2

library(dplyr)
library(ggplot2)
library(tibble)

inner <- inner_join(roster, submissions, by = "learner_id")
left <- left_join(roster, submissions, by = "learner_id")
right <- right_join(roster, submissions, by = "learner_id")
full <- full_join(roster, submissions, by = "learner_id")
semi <- semi_join(roster, submissions, by = "learner_id")
anti <- anti_join(roster, submissions, by = "learner_id")


join_counts <- tibble(
  join = c("Inner", "Left", "Right", "Full", "Semi", "Anti"),
  rows = c(nrow(inner), nrow(left), nrow(right),
           nrow(full), nrow(semi), nrow(anti)),
  submission_fields = c("Yes", "Yes", "Yes",
                        "Yes", "No", "No")
)

join_counts
inner$learner_id
## [1] "L01" "L02" "L03" "L05" "L06"
left$learner_id
## [1] "L01" "L02" "L03" "L04" "L05" "L06" "L07" "L08"
right$learner_id
## [1] "L01" "L02" "L03" "L05" "L06" "L09"
full$learner_id
## [1] "L01" "L02" "L03" "L04" "L05" "L06" "L07" "L08" "L09"
semi$learner_id
## [1] "L01" "L02" "L03" "L05" "L06"
anti$learner_id
## [1] "L04" "L07" "L08"

The joins produce different results because each one follows different rules for retaining records. An inner join keeps only matching IDs, while a left join keeps everyone in the roster. Semi and anti joins only return columns from the roster.

A learner can have a matching submission record but still have an NA score. Therefore, the submission record exists, but the score is missing. We shouldn’t treat missing scores as a learner not submitting their project.

U3

submissions_flagged <- submissions |>
  mutate(has_submission = TRUE)


lab_joined <- roster |>
  left_join(
    submissions_flagged,
    by = "learner_id",
    relationship = "one-to-one"
  ) |>
  mutate(
    has_submission = coalesce(has_submission, FALSE)
  )

lab_joined
anyDuplicated(roster$learner_id)
## [1] 0
anyDuplicated(submissions$learner_id)
## [1] 0
nrow(roster)
## [1] 8
nrow(lab_joined)
## [1] 8
setequal(roster$learner_id, lab_joined$learner_id)
## [1] TRUE
anyDuplicated(lab_joined$learner_id)
## [1] 0
anti_join(roster, submissions, by = "learner_id")
anti_join(submissions, roster, by = "learner_id")
lab_joined |>
  count(has_submission, is.na(score))

I used a left join to retain all enrolled learners. I added has_submission = TRUE to the submissions table before joining and changed unmatched indicator values to FALSE. I did not replace missing scores with zero because a missing score does not necessarily mean the learner received a score of zero. I checked for duplicate IDs, verified that the roster population was retained, confirmed that the output had unique IDs, and identified unmatched records in both directions.

U4

submissions_conflict <- submissions |>
  bind_rows(
    tibble(
      learner_id = "L02",
      project = "joins",
      score = 9
    )
  )


submissions_conflict |>
  add_count(learner_id) |>
  filter(n > 1)
tryCatch(
  {
    roster |>
      left_join(
        submissions_conflict,
        by = "learner_id",
        relationship = "one-to-one"
      )
  },
  error = function(e) {
    cat("Join error:", conditionMessage(e))
  }
)
## Join error: Each row in `x` must match at most 1 row in `y`.
## ℹ Row 2 of `x` matches multiple rows in `y`.
unguarded <- roster |>
  left_join(
    submissions_conflict,
    by = "learner_id"
  )

nrow(unguarded)
## [1] 9

The relationship error occurs because L02 now has more than one submission record, which violates the expected one-to-one relationship. Without the relationship check, the join duplicates the roster information for L02 and increases the output size. Before resolving the conflict, I would need to know whether the second submission was a correction, another attempt, or an accidental duplicate. I would also want submission timestamps, attempt identifiers, or grading records. I would not remove either score without evidence.

U5

pathway_summary <- lab_joined |>
  group_by(pathway) |>
  summarise(
    enrolled = n(),
    matched = sum(has_submission),
    coverage = matched / enrolled,
    observed_scores = sum(!is.na(score)),
    mean_score = if (all(is.na(score))) {
      NA_real_
    } else {
      mean(score, na.rm = TRUE)
    },
    .groups = "drop"
  )

pathway_summary

The coverage denominator is the total number of enrolled learners in each pathway. The mean score denominator is the number of learners with an observed, nonmissing score.

ggplot(pathway_summary,
       aes(x = pathway, y = coverage)) +
  geom_col(fill = "darkgreen", width = 0.6) +
  geom_text(
    aes(label = paste0(matched, "/", enrolled)),
    vjust = -0.5,
    size = 4
  ) +
  scale_y_continuous(
    limits = c(0, 1),
    breaks = seq(0, 1, 0.2),
    labels = function(x) paste0(x * 100, "%"),
    expand = expansion(mult = c(0, 0))
  ) +
  labs(
    title = "Project Submission Coverage by Pathway",
    x = "Pathway",
    y = "Submission Coverage",
    caption = "Labels show matched submissions / enrolled learners"
  ) +
  theme_minimal()

The summary compares project submission coverage and observed scores across the two pathways. Submission coverage is calculated by dividing the number of enrolled learners with matching submission records by the total number enrolled in each pathway. Missing scores are excluded from the mean score calculation, but matching submission records are still counted in coverage. This distinction is important because a missing score does not necessarily indicate that a learner failed to participate. A submission without a matching roster ID is excluded because the report focuses on enrolled learners. These results are descriptive and do not establish that one pathway causes better academic performance. Other factors, such as student preparation, participation, and differences in grading, could influence the observed results.

U6

batch1 <- submissions |> slice(1:3)
batch2 <- submissions |> slice(3:6)


bound <- bind_rows(batch1, batch2)


combined_union <- dplyr::union(batch1, batch2)


nrow(batch1)
## [1] 3
nrow(batch2)
## [1] 4
nrow(bound)
## [1] 7
nrow(combined_union)
## [1] 6
dplyr::setequal(bound, combined_union)
## [1] TRUE
bound |>
  count(across(everything())) |>
  filter(n > 1)
dplyr::setequal(
  bound |> select(learner_id),
  combined_union |> select(learner_id)
)
## [1] TRUE

The two batches overlap at row 3. bind_rows() keeps that row twice, resulting in seven rows. union() removes the exact duplicate, resulting in six rows. Although setequal() returns TRUE, this does not prove that repeated records were preserved because it only compares distinct values. Column binding would be inappropriate because roster and submission rows are not guaranteed to correspond to the same learner by position, even if both tables had the same number of rows.

U7

claimed <- inner_join(
  roster,
  submissions,
  by = "learner_id"
)

claimed |>
  summarise(
    submission_rate = mean(!is.na(score))
  )
claimed_result <- claimed |>
  summarise(
    denominator = n(),
    submission_rate = mean(!is.na(score))
  )


corrected_result <- lab_joined |>
  summarise(
    denominator = n(),
    submission_rate = mean(has_submission)
  )


claimed_result
corrected_result
comparison <- bind_rows(
  claimed_result |> mutate(method = "Flawed"),
  corrected_result |> mutate(method = "Corrected")
)

comparison

I would reject the original suggestion because it does not calculate the intended submission coverage rate. The inner join excludes enrolled learners who do not have matching submission records, resulting in an incorrect denominator. Additionally, checking whether scores are missing measures score availability rather than submission coverage. I corrected the analysis by using a left join to retain all enrolled learners and creating an indicator for matching submission records. The corrected denominator includes the entire enrolled population, while the numerator counts learners with matching submissions. This approach better answers the research question and avoids interpreting missing scores as missing submission records.

G1 (DAAN 703 only)

Joining the tables using only learner_id produces five rows instead of three because P1 appears twice in both tables. This causes the records from different weeks to match incorrectly. When both learner_id and week are used, the join correctly produces three rows with the appropriate scores. The same results can be produced using merge(). However, matching outputs do not guarantee that the original data is accurate because both methods could use incorrect source information.

activity <- tibble(
  learner_id = c("P1", "P1", "P2"),
  week = c(1, 2, 1),
  visits = c(3, 5, 2)
)

quizzes <- tibble(
  learner_id = c("P1", "P1", "P2"),
  week = c(1, 2, 1),
  score = c(6, 8, 7)
)


wrong_join <- left_join(
  activity, quizzes,
  by = "learner_id",
  relationship = "many-to-many"
)

wrong_join
nrow(wrong_join)
## [1] 5
correct_join <- left_join(
  activity, quizzes,
  by = c("learner_id", "week"),
  relationship = "one-to-one"
)

correct_join
nrow(correct_join)
## [1] 3
merged <- merge(
  activity, quizzes,
  by = c("learner_id", "week")
)


correct_sorted <- correct_join |>
  arrange(learner_id, week)

merged_sorted <- merged |>
  arrange(learner_id, week) |>
  select(all_of(names(correct_sorted)))


all.equal(
  as.data.frame(correct_sorted),
  as.data.frame(merged_sorted),
  check.attributes = FALSE
)
## [1] TRUE

G2 (DAAN 703 only)

The roster-based analysis includes all enrolled learners, while the inner join only includes learners with matching submission records. This changes the denominator and can make submission coverage appear higher than it actually is. Both pathways show 100% submission coverage after the inner join because learners without submissions have been removed. Missing grades are also different from missing submission records. For example, L03 submitted a project but does not have a recorded score. One possible explanation for missing records is that some submissions were not captured in the system, but the data does not establish that this occurred.

roster_summary <- lab_joined |>
  group_by(pathway) |>
  summarise(
    enrolled = n(),
    submitted = sum(has_submission),
    graded = sum(!is.na(score)),
    submission_coverage = submitted / enrolled,
    score_coverage = graded / enrolled
  )

roster_summary
inner_data <- inner_join(
  roster, submissions,
  by = "learner_id"
)

inner_summary <- inner_data |>
  group_by(pathway) |>
  summarise(
    matched = n(),
    submitted = n(),
    graded = sum(!is.na(score)),
    submission_coverage = submitted / matched,
    score_coverage = graded / matched
  )

inner_summary

G3 (DAAN 703 only)

Missing learner IDs can cause incorrect matches when joining tables. By default, dplyr may match an NA value from one table with an NA value from another table, even though there is no evidence that the records belong to the same person. Using na_matches = “never” prevents this.

A reasonable approach would be to separate records with missing IDs, investigate their source, and only include them in matched analysis after their identities are verified. Row counts and relationship checks alone cannot prove the join is correct because matching unknown IDs may still produce the expected number of rows without triggering an error.

roster_unknown <- bind_rows(
  roster,
  tibble(
    learner_id = NA_character_,
    pathway = "DASC 240"
  )
)

submissions_unknown <- bind_rows(
  submissions,
  tibble(
    learner_id = NA_character_,
    project = "joins",
    score = 8
  )
)

roster_unknown <- roster_unknown |>
  mutate(in_roster = TRUE)

submissions_unknown <- submissions_unknown |>
  mutate(in_submission = TRUE)


default_join <- left_join(
  roster_unknown,
  submissions_unknown,
  by = "learner_id",
  relationship = "one-to-one"
)


safe_join <- left_join(
  roster_unknown,
  submissions_unknown,
  by = "learner_id",
  relationship = "one-to-one",
  na_matches = "never"
)

default_join |>
  filter(is.na(learner_id))
safe_join |>
  filter(is.na(learner_id))
sum(is.na(roster_unknown$learner_id))
## [1] 1
sum(is.na(submissions_unknown$learner_id))
## [1] 1
nrow(default_join)
## [1] 9
nrow(safe_join)
## [1] 9
roster_quarantine <- roster_unknown |>
  filter(is.na(learner_id))

submissions_quarantine <- submissions_unknown |>
  filter(is.na(learner_id))

roster_quarantine
submissions_quarantine

AI-use disclosure

I used ChatGPT throughout this assignment to help me troubleshoot coding errors, and explore different approaches to joining datasets in R. It was particularly helpful when I encountered errors involving composite keys and join relationships. I reviewed the suggested code and explanations to better understand how different joins affect row counts, data coverage, and the accuracy of results. Overall, using AI helped strengthen my understanding of data wrangling and the importance of validating data before drawing conclusions.