# 데이터마트와 데이터 전처리 — 중복된 연결 키가 행 수와 합계를 늘리는 과정
# 적용 범위: merge() 공식 문서의 복수 일치 행을 모두 반환하는 규칙을 가상의 주문·고객 표로 확인합니다. 주문과 금액은 실제 거래 자료가 아닙니다. 고객 표에는 모든 필드가 같은 행을 의도적으로 한 번 중복 입력했으며, 이 입력에서만 unique()로 동일 행을 정리합니다.
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/base/html/merge.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/base/html/duplicated.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/base/html/unique.html
# 실행 확인 환경: R version 4.6.2 (2026-10-29)
# 아래 코드를 실행하면 출력과 그림을 확인할 수 있습니다.

orders <- data.frame(order_id = 1:3, customer_id = c(1, 1, 2),
  amount = c(10, 20, 30))
lookup <- data.frame(customer_id = c(1, 1, 2), city = c("서울", "서울", "부산"))
duplicated_join <- merge(orders, lookup, by = "customer_id", all.x = TRUE)
clean_lookup <- unique(lookup)
stopifnot(anyDuplicated(clean_lookup$customer_id) == 0L)
clean_join <- merge(orders, clean_lookup, by = "customer_id", all.x = TRUE)
cat("중복 연결 결과:\n"); print(duplicated_join)
comparison <- data.frame(상태 = c("원본 주문", "중복 키로 연결", "키 정리 후 연결"),
  행수 = c(nrow(orders), nrow(duplicated_join), nrow(clean_join)),
  금액합계 = c(sum(orders$amount), sum(duplicated_join$amount), sum(clean_join$amount)))
print(comparison)
cat("중복 연결에서 주문별 출현 횟수:\n")
print(table(duplicated_join$order_id))
par(mfrow = c(1, 2), mar = c(4.5, 4.5, 3.5, 1))
colours <- c("#6B7280", "#D97706", "#2563EB")
labels <- c("원본", "중복 연결", "키 정리")
positions <- barplot(comparison$행수, names.arg = labels, ylim = c(0, 6),
  col = colours, main = "조인 전후 행 수", ylab = "행 수")
text(positions, comparison$행수 + 0.25, comparison$행수)
positions <- barplot(comparison$금액합계, names.arg = labels, ylim = c(0, 110),
  col = colours, main = "조인 전후 금액 합계", ylab = "가상 금액 단위")
text(positions, comparison$금액합계 + 5, comparison$금액합계)
