# R 프로그래밍 기초 — 팩터의 내부 코드와 숫자 라벨 구분하기
# 적용 범위: 입력값과 비교표·그림은 새로 작성했습니다. factor 문서 Warning에 제시된 as.numeric(levels(f))[f] 변환을 사용합니다. 이 예제는 라벨이 모두 숫자로 해석되는 경우입니다.
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/base/html/factor.html
# 실행 확인 환경: R version 4.6.2 (2026-10-29)
# 아래 코드를 실행하면 출력과 그림을 확인할 수 있습니다.

# 재현 설정: 같은 난수 방식과 출력 자릿수를 사용합니다.
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(2026)
options(width = 90, digits = 7, scipen = 7)

f <- factor(c("10", "20", "10", "30"), levels = c("10", "20", "30"))
internal <- as.numeric(f)
restored <- as.numeric(levels(f))[f]
data.frame(표시문자 = as.character(f), 내부코드 = internal, 숫자라벨 = restored)
c(객체클래스 = class(f), 내부자료형 = typeof(f))
matplot(seq_along(f), cbind(internal, restored), type = "b",
        pch = c(16, 17), lty = c(2, 1), col = c("#DC2626", "#2563EB"),
        xaxt = "n", xlab = "입력의 행 위치", ylab = "숫자로 변환한 결과",
        main = "수준 번호와 숫자 라벨은 다른 값")
axis(1, at = seq_along(f), labels = paste0(seq_along(f), "행"))
legend("topleft", c("as.numeric(f): 내부 코드", "수준에서 복원한 숫자"),
       col = c("#DC2626", "#2563EB"), pch = c(16, 17), lty = c(2, 1), bty = "n")
