# 📦 1. 필수 패키지 설치 및 로드
install.packages(c("readr", "car", "broom", "writexl"), dependencies = TRUE)
library(readr)
library(car)
library(broom)
library(writexl)
library(dplyr)
# 📂 2. 데이터 불러오기
data1 <- read_csv("2025.04.18-1coding.csv")
# 🔠 3. 요인 변수 변환
data1$group <- factor(data1$group, levels = c(1, 2), labels = c("정상군", "인지손상군"))
data1$condition <- factor(data1$condition, levels = c(1, 2, 3), labels = c("평지", "물컵", "숫자세기"))
# ✅ 4. 종속변수 목록 (velocity 포함)
gait_vars <- c(
"loadingresponsetime", "loadingresponsegc", "midstancetime", "midstancegc",
"terminalstancetime", "terminalstancegc", "preswingtime", "preswinggc",
"swingphase", "swingsi", "cadence", "cadencero", "cadencesi",
"stancephasetime", "stancesi", "cofsi", "velocity"
)
# ✅ 5. 공식 정의
formula <- as.formula(paste0(
"cbind(", paste(gait_vars, collapse = ", "), ") ~ group * condition + age + height + edu"
))
# ✅ 6. MANOVA 수행
model <- manova(formula, data = data1)
# ✅ 7. Univariate ANOVA 결과 정리
aov_summary <- summary.aov(model)
result_list <- list()
for (i in seq_along(aov_summary)) {
df <- as.data.frame(aov_summary[[i]])
variable_name <- names(aov_summary)[i]
df$Effect <- rownames(df)
df$Variable <- variable_name
result_list[[i]] <- df
}
anova_df <- bind_rows(result_list) %>%
select(Variable, Effect, everything())
# ✅ 8. MANOVA 결과 (Pillai’s trace 등)
manova_pillai <- summary(model, test = "Pillai")
pillai_df <- as.data.frame(manova_pillai$stats)
pillai_df$Effect <- rownames(pillai_df)
pillai_df <- pillai_df[, c("Effect", "Pillai", "approx F", "num Df", "den Df", "Pr(>F)")]
colnames(pillai_df) <- c("Effect", "Pillai", "F_approx", "num_Df", "den_Df", "P_value")
# ✅ 9. 엑셀로 결과 저장
write_xlsx(
list(
"MANOVA_Pillai" = pillai_df,
"Univariate_ANOVA" = anova_df
),
path = "TwoWay_MANCOVA_with_Effect.xlsx"
)