# 차원 축소 — 주성분분석(PCA)과 다차원척도법(MDS) — 표준화 자료와 적재량을 곱해 PC1 점수 재계산
# 적용 범위: 연결한 R 공식문서의 함수·반환값 정의를 학습자료에 적용한 응용 예제입니다. 입력 자료의 성격은 위에 명시했으며, 표시 코드·콘솔 출력·R 그림은 사전 실행해 함께 생성했습니다.
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/prcomp.html
# 실행 확인 환경: R version 4.6.2 (2026-10-29)
# 아래 코드를 실행하면 출력과 그림을 확인할 수 있습니다.

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

fit <- prcomp(USArrests, scale. = TRUE)
z <- scale(USArrests, center=fit$center, scale=fit$scale)
# 주성분 축의 부호는 임의이므로 두 계산에 같은 방향을 적용합니다.
direction <- if (fit$rotation["Assault",1] < 0) -1 else 1
manual <- as.vector(z %*% fit$rotation[,1]) * direction
r_score <- fit$x[,1] * direction
round(head(cbind(직접계산=manual, R점수=r_score),6),4)
round(max(abs(manual-r_score)),10)
par(pty="s")
plot(manual,r_score,pch=19,col="#2563EB",asp=1,
     main="PC1 점수의 행렬곱 확인",xlab="직접 계산한 PC1 점수",ylab="R prcomp의 PC1 점수")
abline(0,1,col="#DC2626",lty=2)
