library(readr)
library(moonBook)
library(dplyr)
library(car)
library(effsize)
library(rstatix)
library(DescTools)
library(ggplot2)
library(tidyr)
library(forcats)
library(rpart)
library(rpart.plot)
library(caret)
library(future)
library(rattle)
library(pROC) 
library(mice)
library(ggalluvial)

total <- read_csv("total_mrc_rere.csv")

categorical_vars <- c("group", "sex", "dx_code", "side", "HTN", 
                      "DM", "Dyslipidemia", "A_fib", "time_1809", 
                      "time_1909", "Modality")

continuous_vars <- c("age", "bmi", "FMLL_lesion_pre", "FMLL_variation", 
                     "MBI_pre", "MBI_variation", "MMSE_pre", "MMSE_variation",
                     "FAC_variation", "BBS_pre", "BBS_variation", "MRC_pre", 
                     "MRC_variation", "FAC_pre", "Sessions", "Dx_to_Round")

total[categorical_vars] <- lapply(total[categorical_vars], as.factor)

total$FAC_pre <- as.factor(total$FAC_pre)
total$FAC_post <-as.factor(total$FAC_post)
str(total$FAC_pre)  
str(total$FAC_post)


# ─────────────────────────────────────────────────────────────────────────────
# 2) 데이터 준비: group이 "C"인 행만 골라 FAC_pre→FAC_post별 환자 수 집계
# ─────────────────────────────────────────────────────────────────────────────
c_df <- total %>%
  filter(group == "C", !is.na(FAC_pre), !is.na(FAC_post)) %>%
  count(FAC_pre, FAC_post) %>%
  ungroup()

# ─────────────────────────────────────────────────────────────────────────────
# 3) “C” 그룹용 Alluvial 플롯
# ─────────────────────────────────────────────────────────────────────────────
p_C <- ggplot(c_df,
              aes(
                axis1 = FAC_pre,     # 왼쪽 축: baseline FAC
                axis2 = FAC_post,    # 오른쪽 축: follow‐up FAC
                y     = n            # 각 흐름의 환자 수(높이)
              )) +
  # 3.1) Baseline→Follow‐up FAC 흐름을 곡선으로 그림
  geom_alluvium(aes(fill = FAC_pre), width = 1/4, alpha = 0.7) +
  # 3.2) 왼쪽 축(FAC_pre) 사다리꼴 표시
  geom_stratum(aes(x = 1, stratum = FAC_pre, fill = FAC_pre),
               width = 1/4, color = "black") +
  # 3.3) 오른쪽 축(FAC_post) 사다리꼴 표시
  geom_stratum(aes(x = 2, stratum = FAC_post, fill = FAC_post),
               width = 1/4, color = "black") +
  # 3.4) 각 사다리꼴 내부에 FAC 레벨 텍스트(label) 출력
  geom_text(
    stat = "stratum",
    aes(
      x       = after_stat(x), 
      stratum = after_stat(stratum),
      label   = after_stat(stratum)
    ),
    size  = 0,
    color = "Black"
  ) +
  # 3.5) X축 단계별 레이블 (Baseline vs Follow‐up)
  scale_x_discrete(
    limits = c("Baseline (FAC_pre)", "Follow-up (FAC_post)"),
    expand = c(.01, .01)
  ) +
  # 3.6) FAC_pre 색상 팔레트 (범주형)
  scale_fill_brewer(type = "qual", palette = "Set2", name = "FAC Level") +
  # 3.7) 제목 및 축 레이블
  labs(
    title = "Group C: FAC_pre vs. FAC_post",
    x     = NULL,
    y     = "Number of Patients"
  ) +
  # 3.8) 최소 테마 설정 (Y축 눈금/눈금선 제거)
  theme_minimal(base_size = 12) +
  theme(
    legend.position    = "none",
    axis.text.y         = element_blank(),
    axis.ticks.y        = element_blank(),
    panel.grid.major.y  = element_blank()
  )

# ─────────────────────────────────────────────────────────────────────────────
# 4) 데이터 준비: group이 "R"인 행만 골라 FAC_pre→FAC_post별 환자 수 집계
# ─────────────────────────────────────────────────────────────────────────────
r_df <- total %>%
  filter(group == "R", !is.na(FAC_pre), !is.na(FAC_post)) %>%
  count(FAC_pre, FAC_post) %>%
  ungroup()

# ─────────────────────────────────────────────────────────────────────────────
# 5) “R” 그룹용 Alluvial 플롯 (코드 구조는 p_C와 동일하되, 데이터만 다릅니다)
# ─────────────────────────────────────────────────────────────────────────────
p_R <- ggplot(r_df,
              aes(
                axis1 = FAC_pre,
                axis2 = FAC_post,
                y     = n
              )) +
  geom_alluvium(aes(fill = FAC_pre), width = 1/4, alpha = 0.7) +
  geom_stratum(aes(x = 1, stratum = FAC_pre, fill = FAC_pre),
               width = 1/4, color = "black") +
  geom_stratum(aes(x = 2, stratum = FAC_post, fill = FAC_post),
               width = 1/4, color = "black") +
  geom_text(
    stat = "stratum",
    aes(
      x       = after_stat(x),
      stratum = after_stat(stratum),
      label   = after_stat(stratum)
    ),
    size  = 0,
    color = "black"
  ) +
  scale_x_discrete(
    limits = c("Baseline (FAC_pre)", "Follow-up (FAC_post)"),
    expand = c(.01, .01)
  ) +
  scale_fill_brewer(type = "qual", palette = "Set2", name = "FAC Level") +
  labs(
    title = "Group R: FAC_pre vs. FAC_post",
    x     = NULL,
    y     = "Number of Patients"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    legend.position    = "none",
    axis.text.y         = element_blank(),
    axis.ticks.y        = element_blank(),
    panel.grid.major.y  = element_blank()
  )

# ─────────────────────────────────────────────────────────────────────────────
# 6) 결과 확인: 각각의 플롯을 개별적으로 출력하거나, patchwork 등으로 나란히 배치
# ─────────────────────────────────────────────────────────────────────────────
# (1) 개별 출력
print(p_C)
print(p_R)


mytable (group~FAC_pre + FAC_post, data=total)


alluv_df <- total %>%
  filter(!is.na(FAC_pre), !is.na(FAC_post)) %>%  # 결측치 제외
  count(FAC_pre, FAC_post) %>%
  ungroup()

ggplot(alluv_df,
       aes(
         axis1 = FAC_pre,     # 왼쪽 축: baseline FAC
         axis2 = FAC_post,    # 오른쪽 축: follow‐up FAC
         y     = n            # 각 흐름의 환자 수
       )) +
  # 겹쳐진 흐름을 곡선으로 나타냄 (‘fill’로 FAC_pre 기준 색상 지정)
  geom_alluvium(aes(fill = FAC_pre), width = 1/12, alpha = 0.7) +
  # 왼쪽/오른쪽 축에 각 범주(사다리꼴) 표시
  geom_stratum(aes(fill = FAC_pre), width = 1/12, color = "black") +
  # 사다리꼴 위에 각 FAC 범주 레이블(0,1,2…)을 텍스트로 추가
  geom_text(stat = "stratum",
            aes(label = after_stat(stratum)),
            size = 3,
            color = "black") +
  # X축 레이블을 두 단계로 지정
  scale_x_discrete(
    limits = c("Baseline (FAC_pre)", "Follow-up (FAC_post)"),
    expand = c(.05, .05)
  ) +
  # 색상 팔레트 설정 (FAC_pre 범주에 따라 색 지정)
  scale_fill_brewer(type = "qual", palette = "Set2", name = "FAC Level") +
  # 제목 및 축 레이블
  labs(
    title = "FAC_pre vs. FAC_post: Paired Alluvial Plot",
    x     = NULL,
    y     = "Number of Patients"
  ) +
  # 최소한의 테마로 깔끔하게 표시
  theme_minimal(base_size = 12) +
  theme(
    legend.position = "right",
    axis.text.y      = element_blank(),  # Y축 눈금 숨김
    axis.ticks.y     = element_blank(),
    panel.grid.major.y = element_blank()
  )

mytable(group~age+sex+bmi+dx_code+side+HTN+DM+Dyslipidemia+A_fib+FMLL_lesion_pre
        +FMLL_variation+MBI_pre+MBI_variation+MMSE_pre+MMSE_variation+FAC_pre
        +FAC_variation+BBS_pre+BBS_variation+MRC_pre+MRC_variation+Sessions, 
        data=total, method=3)


d1 <- cohen.d(Sessions ~ group, data = total)
print(d1)

# Effector 정의: FAC1 이상 증가
total$FAC_pre <- as.numeric(as.character(total$FAC_pre))

total <- total %>% filter(FAC_pre < 5)

total <- total %>%
  mutate(outcome = ifelse(FAC_variation >= 1, "effector", "noneffector"))

# outcome 변수를 factor로 변환
total$outcome <- factor(total$outcome, levels = c("noneffector", "effector"))
total$outcome <- ifelse(total$outcome == "effector", 1, 0)

mytable (group~outcome, data=total, method =1)

tbl_outcome <- table(total$group, total$outcome)
cram_outcome <- CramerV(tbl_outcome)
cat("Cramér's V (outcome vs group):", round(cram_outcome, 3), "\n")

total_model <- glm(outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre 
                   + BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM + 
                     Dyslipidemia + A_fib + group + Sessions, 
                   data = total, 
                   family = binomial)
extractOR(total_model)

vif(total_model)




robot <- read_csv("robot_mrc_rere.csv")

categorical_vars <- c("group", "sex", "dx_code", "side", "HTN", 
                      "DM", "Dyslipidemia", "A_fib", "time_1809", 
                      "time_1909", "Modality", "first")

continuous_vars <- c("age", "bmi", "FMLL_lesion_pre", "FMLL_variation", 
                     "MBI_pre", "MBI_variation", "MMSE_pre", "MMSE_variation",
                     "FAC_variation", "BBS_pre", "BBS_variation", "MRC_pre", 
                     "MRC_variation", "FAC_pre", "Sessions", "Dx_to_Round")

robot[categorical_vars] <- lapply(robot[categorical_vars], as.factor)

robot$FAC_pre <- as.factor(robot$FAC_pre)
robot$FAC_post <-as.factor(robot$FAC_post)
str(robot$FAC_pre)  
str(robot$FAC_post)


alluv_df <- robot %>%
  filter(!is.na(FAC_pre), !is.na(FAC_post)) %>%  # 결측치 제외
  count(FAC_pre, FAC_post) %>%
  ungroup()

ggplot(alluv_df,
       aes(
         axis1 = FAC_pre,     # 왼쪽 축: baseline FAC
         axis2 = FAC_post,    # 오른쪽 축: follow‐up FAC
         y     = n            # 각 흐름의 환자 수
       )) +
  # 겹쳐진 흐름을 곡선으로 나타냄 (‘fill’로 FAC_pre 기준 색상 지정)
  geom_alluvium(aes(fill = FAC_pre), width = 1/12, alpha = 0.7) +
  # 왼쪽/오른쪽 축에 각 범주(사다리꼴) 표시
  geom_stratum(aes(fill = FAC_pre), width = 1/12, color = "black") +
  # 사다리꼴 위에 각 FAC 범주 레이블(0,1,2…)을 텍스트로 추가
  geom_text(stat = "stratum",
            aes(label = after_stat(stratum)),
            size = 3,
            color = "black") +
  # X축 레이블을 두 단계로 지정
  scale_x_discrete(
    limits = c("Baseline (FAC_pre)", "Follow-up (FAC_post)"),
    expand = c(.05, .05)
  ) +
  # 색상 팔레트 설정 (FAC_pre 범주에 따라 색 지정)
  scale_fill_brewer(type = "qual", palette = "Set2", name = "FAC Level") +
  # 제목 및 축 레이블
  labs(
    title = "FAC_pre vs. FAC_post: Paired Alluvial Plot",
    x     = NULL,
    y     = "Number of Patients"
  ) +
  # 최소한의 테마로 깔끔하게 표시
  theme_minimal(base_size = 12) +
  theme(
    legend.position = "right",
    axis.text.y      = element_blank(),  # Y축 눈금 숨김
    axis.ticks.y     = element_blank(),
    panel.grid.major.y = element_blank()
  )


mytable(Modality~age+sex+bmi+dx_code+side+HTN+DM+Dyslipidemia+A_fib+FMLL_lesion_pre
        +FMLL_variation+MBI_pre+MBI_variation+MMSE_pre+MMSE_variation+FAC_pre
        +FAC_variation+BBS_pre+BBS_variation+MRC_pre+MRC_variation+outcome+Sessions
        +Dx_to_Round, 
        data=robot, method=1)

mytable(first~age+sex+bmi+dx_code+side+HTN+DM+Dyslipidemia+A_fib+FMLL_lesion_pre
        +FMLL_variation+MBI_pre+MBI_variation+MMSE_pre+MMSE_variation+FAC_pre
        +FAC_variation+BBS_pre+BBS_variation+MRC_pre+MRC_variation+outcome+Sessions
        +Dx_to_Round, 
        data=robot, method=1)


# Effector 정의: FAC1 이상 증가
robot$FAC_pre <- as.numeric(as.character(robot$FAC_pre))

robot <- robot %>% filter(FAC_pre < 5)

robot <- robot %>%
  mutate(outcome = ifelse(FAC_variation >= 1, "effector", "noneffector"))

# outcome 변수를 factor로 변환
robot$outcome <- factor(robot$outcome, levels = c("noneffector", "effector"))
total$outcome <- ifelse(total$outcome == "effector", 1, 0)

mytable (Modality~outcome, data=robot, method =1)
mytable (first~outcome, data=robot, method =1)

robot_model_com <- glm(outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre 
                   + BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM + 
                     Dyslipidemia + A_fib + Sessions + Dx_to_Round + Modality, 
                   data = robot, 
                   family = binomial)
extractOR(robot_model_com)

vif(robot_model_com)

robot_model <- glm(outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre 
                   + BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM + 
                     Dyslipidemia + A_fib + Sessions + Dx_to_Round + first, 
                   data = robot, 
                   family = binomial)
extractOR(robot_model)

vif(robot_model)

## Violin plot 그리기
# 1) 시각화할 변수 목록
robot$FAC_pre<-as.numeric(robot$FAC_pre)
variables <- c("FMLL_lesion_pre", "MBI_pre", "MMSE_pre", 
               "FAC_pre", "BBS_pre", "MRC_pre")

# 2) long 포맷으로 변환
robot_long <- robot %>%
  select(first, all_of(variables)) %>%
  pivot_longer(
    cols      = -first,
    names_to  = "Variable",
    values_to = "Value"
  ) %>%
  filter(!is.na(Value)) %>%
  mutate(
    first    =  factor(first, levels = unique(first)),
    Variable = factor(Variable, levels = variables)
  )

summary_data <- robot_long %>%
  group_by(first, Variable) %>%
  summarise(
    Mean  = mean(Value),
    SD    = sd(Value),
    .groups = "drop"
  ) %>%
  mutate(
    Lower = Mean - SD,
    Upper = Mean + SD,
    xpos  = as.numeric(first)               # x 위치 숫자화
  )

# 3) 변수명 레이블 매핑 (선택)
variable_labels <- c(
  FMLL_lesion_pre = "Initial FMLL Lesion",
  MBI_pre         = "Initial MBI",
  MMSE_pre        = "Initial MMSE",
  FAC_pre         = "Initial FAC",
  BBS_pre         = "Initial BBS",
  MRC_pre         = "Initial MRC"
)

# 4) violin plot 그리기
ggplot(robot_long, aes(x = first, y = Value, fill = first)) +
  geom_violin(trim = FALSE, alpha = 0.6, colour = NA) +
  stat_summary(
    fun   = mean,
    geom  = "point",
    shape = 23,
    size  = 2,
    fill  = "white",
    colour= "black"
  ) +
  facet_wrap(~ Variable, scales = "free_y", 
             labeller = as_labeller(variable_labels)) +
  scale_fill_brewer(palette = "Set2") +
  labs(
    title = "Baseline Feature Distributions by First Group",
    x     = "First Group",
    y     = "Value",
    fill  = "Group"
  ) +
  theme_minimal(base_size = 14) +
  theme(
    legend.position   = "right",
    axis.text.x       = element_text(angle = 45, hjust = 1),
    strip.text        = element_text(face = "bold", size = 12)
  )


summary_data <- summary_data %>%
  mutate(
    first = factor(first, 
                   levels = c("Erigo", "LOKOMAT", "MorningWalk", "ANDAGO", "EXOWALK")),
    xpos  = as.numeric(first)    # 다시 숫자 매핑
  )

# 5) 떠 있는 박스 플롯 그리기
ggplot(summary_data, aes(x=xpos, fill=first)) +
  # Mean±SD 박스
  geom_rect(aes(
    xmin = xpos - 0.3,
    xmax = xpos + 0.3,
    ymin = Lower,
    ymax = Upper
  ), alpha=0.6, colour="black") +
  # 평균선
  geom_segment(aes(
    x    = xpos - 0.3,
    xend = xpos + 0.3,
    y    = Mean,
    yend = Mean
  ), size=1, colour="black") +
  # facet 변수별
  facet_wrap(~ Variable, scales="free_y",
             labeller = as_labeller(variable_labels)) +
  scale_x_continuous(
    breaks = 1:5,
    labels = c("Erigo","LOKOMAT","MorningWalk","ANDAGO","EXOWALK")
  ) +
  scale_fill_brewer(palette="Set2", name="First Group") +
  labs(
    title = "Floating Box Plot: Mean ± SD by First Group",
    x     = "First Group",
    y     = "Value"
  ) +
  theme_minimal(base_size=14) +
  theme(
    legend.position = "right",
    axis.text.x     = element_text(angle=45, hjust=1),
    strip.text      = element_text(face="bold")
  )

##로봇별 데이터 만들기
total_sep <- read_csv("total_mrc_rere.csv")

categorical_vars <- c("group", "sex", "dx_code", "side", "HTN", 
                      "DM", "Dyslipidemia", "A_fib", "time_1809", 
                      "time_1909", "Modality")

continuous_vars <- c("age", "bmi", "FMLL_lesion_pre", "FMLL_variation", 
                     "MBI_pre", "MBI_variation", "MMSE_pre", "MMSE_variation",
                     "FAC_variation", "BBS_pre", "BBS_variation", "MRC_pre", 
                     "MRC_variation", "FAC_pre", "Sessions", "Dx_to_Round")

total_sep[categorical_vars] <- lapply(total_sep[categorical_vars], as.factor)
total_sep$FAC_pre <- as.factor(total_sep$FAC_pre)




# ANDAGO
ANDAGO <- total_sep %>%
  filter(Modality %in% c("NDT", "ANDAGO")) %>%
  droplevels()

# Erigo
Erigo <- total_sep %>%
  filter(Modality %in% c("NDT", "Erigo")) %>%
  droplevels()

# LOKOMAT
LOKOMAT <- total_sep %>%
  filter(Modality %in% c("NDT", "LOKOMAT")) %>%
  droplevels()

# MorningWalk
MorningWalk <- total_sep %>%
  filter(Modality %in% c("NDT", "MorningWalk")) %>%
  droplevels()

# EXOWALK
EXOWALK <- total_sep %>%
  filter(Modality %in% c("NDT", "EXOWALK")) %>%
  droplevels()

# Combined
Combined <- total_sep %>%
  filter(Modality %in% c("NDT", "Combined")) %>%
  droplevels()

mytable(Modality~age+sex+bmi+dx_code+side+HTN+DM+Dyslipidemia+A_fib+FMLL_lesion_pre
        +FMLL_variation+MBI_pre+MBI_variation+MMSE_pre+MMSE_variation+FAC_pre
        +FAC_variation+BBS_pre+BBS_variation+MRC_pre+MRC_variation+Sessions, 
        data=ANDAGO, method=1)

mytable(Modality~age+sex+bmi+dx_code+side+HTN+DM+Dyslipidemia+A_fib+FMLL_lesion_pre
        +FMLL_variation+MBI_pre+MBI_variation+MMSE_pre+MMSE_variation+FAC_pre
        +FAC_variation+BBS_pre+BBS_variation+MRC_pre+MRC_variation+Sessions, 
        data=Erigo, method=1)

mytable(Modality~age+sex+bmi+dx_code+side+HTN+DM+Dyslipidemia+A_fib+FMLL_lesion_pre
        +FMLL_variation+MBI_pre+MBI_variation+MMSE_pre+MMSE_variation+FAC_pre
        +FAC_variation+BBS_pre+BBS_variation+MRC_pre+MRC_variation+Sessions, 
        data=LOKOMAT, method=1)

mytable(Modality~age+sex+bmi+dx_code+side+HTN+DM+Dyslipidemia+A_fib+FMLL_lesion_pre
        +FMLL_variation+MBI_pre+MBI_variation+MMSE_pre+MMSE_variation+FAC_pre
        +FAC_variation+BBS_pre+BBS_variation+MRC_pre+MRC_variation+Sessions, 
        data=MorningWalk, method=1)

mytable(Modality~age+sex+bmi+dx_code+side+HTN+DM+Dyslipidemia+A_fib+FMLL_lesion_pre
        +FMLL_variation+MBI_pre+MBI_variation+MMSE_pre+MMSE_variation+FAC_pre
        +FAC_variation+BBS_pre+BBS_variation+MRC_pre+MRC_variation+Sessions, 
        data=EXOWALK, method=1)

mytable(Modality~age+sex+bmi+dx_code+side+HTN+DM+Dyslipidemia+A_fib+FMLL_lesion_pre
        +FMLL_variation+MBI_pre+MBI_variation+MMSE_pre+MMSE_variation+FAC_pre
        +FAC_variation+BBS_pre+BBS_variation+MRC_pre+MRC_variation+Sessions, 
        data=Combined, method=1)

# Effector 정의: FAC1 이상 증가
ANDAGO$FAC_pre <- as.numeric(as.character(ANDAGO$FAC_pre))

ANDAGO <- ANDAGO %>% filter(FAC_pre < 5)

ANDAGO <- ANDAGO %>%
  mutate(outcome = ifelse(FAC_variation >= 1, "effector", "noneffector"))

# outcome 변수를 factor로 변환
ANDAGO$outcome <- factor(ANDAGO$outcome, levels = c("noneffector", "effector"))
ANDAGO$outcome <- ifelse(ANDAGO$outcome == "effector", 1, 0)

ANDAGO$Modality <- factor(ANDAGO$Modality, levels = c("NDT", "ANDAGO"))
ANDAGO$Modality <- ifelse(ANDAGO$Modality == "NDT", 0, 1)


mytable (Modality~outcome, data=ANDAGO, method =1)

ANDAGO_model <- glm(outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre 
                       + BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM + 
                         Dyslipidemia + A_fib + Sessions + Modality, 
                       data = ANDAGO, 
                       family = binomial)
extractOR(ANDAGO_model)

vif(ANDAGO_model)


# Effector 정의: FAC1 이상 증가
Erigo$FAC_pre <- as.numeric(as.character(Erigo$FAC_pre))

Erigo <- Erigo %>% filter(FAC_pre < 5)

Erigo <- Erigo %>%
  mutate(outcome = ifelse(FAC_variation >= 1, "effector", "noneffector"))

# outcome 변수를 factor로 변환
Erigo$outcome <- factor(Erigo$outcome, levels = c("noneffector", "effector"))

Erigo$Modality <- factor(Erigo$Modality, levels = c("NDT", "Erigo"))
Erigo$Modality <- ifelse(Erigo$Modality == "NDT", 0, 1)

mytable (Modality~outcome, data=Erigo, method =1)

Erigo_model <- glm(outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre 
                    + BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM + 
                      Dyslipidemia + A_fib + Sessions + Modality, 
                    data = Erigo, 
                    family = binomial)
extractOR(Erigo_model)

vif(Erigo_model)


# Effector 정의: FAC1 이상 증가
LOKOMAT$FAC_pre <- as.numeric(as.character(LOKOMAT$FAC_pre))

LOKOMAT <- LOKOMAT %>% filter(FAC_pre < 5)

LOKOMAT <- LOKOMAT %>%
  mutate(outcome = ifelse(FAC_variation >= 1, "effector", "noneffector"))

# outcome 변수를 factor로 변환
LOKOMAT$outcome <- factor(LOKOMAT$outcome, levels = c("noneffector", "effector"))

LOKOMAT$Modality <- factor(LOKOMAT$Modality, levels = c("NDT", "LOKOMAT"))
LOKOMAT$Modality <- ifelse(LOKOMAT$Modality == "NDT", 0, 1)

mytable (Modality~outcome, data=LOKOMAT, method =1)

LOKOMAT_model <- glm(outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre 
                   + BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM + 
                     Dyslipidemia + A_fib + Sessions + Modality, 
                   data = LOKOMAT, 
                   family = binomial)
extractOR(LOKOMAT_model)

vif(LOKOMAT_model)

LOKOMAT1 <- total_sep %>%
  filter(Modality %in% c("NDT", "LOKOMAT")) %>%
  filter(Modality == "NDT" | (Modality == "LOKOMAT" & time_1909 == 0)) %>%
  droplevels()

# FAC_pre 전처리 및 effector 정의
LOKOMAT1$FAC_pre <- as.numeric(as.character(LOKOMAT1$FAC_pre))
LOKOMAT1 <- LOKOMAT1 %>% filter(FAC_pre < 5)
LOKOMAT1 <- LOKOMAT1 %>%
  mutate(outcome = ifelse(FAC_variation >= 1, "effector", "noneffector"))
LOKOMAT1$outcome   <- factor(LOKOMAT1$outcome, levels = c("noneffector", "effector"))
LOKOMAT1$Modality  <- factor(LOKOMAT1$Modality, levels = c("NDT", "LOKOMAT"))
LOKOMAT1$Modality  <- ifelse(LOKOMAT1$Modality == "NDT", 0, 1)

cat("=== LOKOMAT_model1: Lokomat_pre (time_1909=0) vs NDT ===\n")
cat("N: NDT =", sum(LOKOMAT1$Modality==0),
    "| Lokomat_pre =", sum(LOKOMAT1$Modality==1), "\n")
mytable(Modality ~ outcome, data = LOKOMAT1, method = 1)

LOKOMAT_model1 <- glm(
  outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre +
    BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM +
    Dyslipidemia + A_fib + Sessions + Modality,
  data   = LOKOMAT1,
  family = binomial
)
extractOR(LOKOMAT_model1)
vif(LOKOMAT_model1)

LOKOMAT2 <- total_sep %>%
  filter(Modality %in% c("NDT", "LOKOMAT")) %>%
  filter(Modality == "NDT" | (Modality == "LOKOMAT" & time_1909 == 1)) %>%
  droplevels()

# FAC_pre 전처리 및 effector 정의
LOKOMAT2$FAC_pre <- as.numeric(as.character(LOKOMAT2$FAC_pre))
LOKOMAT2 <- LOKOMAT2 %>% filter(FAC_pre < 5)
LOKOMAT2 <- LOKOMAT2 %>%
  mutate(outcome = ifelse(FAC_variation >= 1, "effector", "noneffector"))
LOKOMAT2$outcome   <- factor(LOKOMAT2$outcome, levels = c("noneffector", "effector"))
LOKOMAT2$Modality  <- factor(LOKOMAT2$Modality, levels = c("NDT", "LOKOMAT"))
LOKOMAT2$Modality  <- ifelse(LOKOMAT2$Modality == "NDT", 0, 1)

cat("\n=== LOKOMAT_model2: Lokomat_post (time_1909=1) vs NDT ===\n")
cat("N: NDT =", sum(LOKOMAT2$Modality==0),
    "| Lokomat_post =", sum(LOKOMAT2$Modality==1), "\n")
mytable(Modality ~ outcome, data = LOKOMAT2, method = 1)

LOKOMAT_model2 <- glm(
  outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre +
    BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM +
    Dyslipidemia + A_fib + Sessions + Modality,
  data   = LOKOMAT2,
  family = binomial
)
extractOR(LOKOMAT_model2)
vif(LOKOMAT_model2)


# Effector 정의: FAC1 이상 증가
MorningWalk$FAC_pre <- as.numeric(as.character(MorningWalk$FAC_pre))

MorningWalk <- MorningWalk %>% filter(FAC_pre < 5)

MorningWalk <- MorningWalk %>%
  mutate(outcome = ifelse(FAC_variation >= 1, "effector", "noneffector"))

# outcome 변수를 factor로 변환
MorningWalk$outcome <- factor(MorningWalk$outcome, levels = c("noneffector", "effector"))

MorningWalk$Modality <- factor(MorningWalk$Modality, levels = c("NDT", "MorningWalk"))
MorningWalk$Modality <- ifelse(MorningWalk$Modality == "NDT", 0, 1)

mytable (Modality~outcome, data=MorningWalk, method =1)

MorningWalk_model <- glm(outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre 
                     + BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM + 
                       Dyslipidemia + A_fib + Sessions + Modality, 
                     data = MorningWalk, 
                     family = binomial)
extractOR(MorningWalk_model)

vif(MorningWalk_model)


# Effector 정의: FAC1 이상 증가
EXOWALK$FAC_pre <- as.numeric(as.character(EXOWALK$FAC_pre))

EXOWALK <- EXOWALK %>% filter(FAC_pre < 5)

EXOWALK <- EXOWALK %>%
  mutate(outcome = ifelse(FAC_variation >= 1, "effector", "noneffector"))

# outcome 변수를 factor로 변환
EXOWALK$outcome <- factor(EXOWALK$outcome, levels = c("noneffector", "effector"))

EXOWALK$Modality <- factor(EXOWALK$Modality, levels = c("NDT", "EXOWALK"))
EXOWALK$Modality <- ifelse(EXOWALK$Modality == "NDT", 0, 1)

mytable (Modality~outcome, data=EXOWALK, method =1)

EXOWALK_model <- glm(outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre 
                         + BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM + 
                           Dyslipidemia + A_fib + Sessions + Modality, 
                         data = EXOWALK, 
                         family = binomial)
extractOR(EXOWALK_model)

vif(EXOWALK_model)


# Effector 정의: FAC1 이상 증가
Combined$FAC_pre <- as.numeric(as.character(Combined$FAC_pre))

Combined <- Combined %>% filter(FAC_pre < 5)

Combined <- Combined %>%
  mutate(outcome = ifelse(FAC_variation >= 1, "effector", "noneffector"))

# outcome 변수를 factor로 변환
Combined$outcome <- factor(Combined$outcome, levels = c("noneffector", "effector"))

Combined$Modality <- factor(Combined$Modality, levels = c("NDT", "Combined"))
Combined$Modality <- ifelse(Combined$Modality == "NDT", 0, 1)

mytable (Modality~outcome, data=Combined, method =1)

Combined_model <- glm(outcome ~ age + sex + dx_code + FAC_pre + MBI_pre + MRC_pre 
                     + BBS_pre + MMSE_pre + FMLL_lesion_pre + HTN + DM + 
                       Dyslipidemia + A_fib + Sessions + Modality, 
                     data = Combined, 
                     family = binomial)
extractOR(Combined_model)

vif(Combined_model)





## effector tree
table(robot$outcome)

tree_simple <- rpart(
  formula = outcome ~ FMLL_lesion_pre + FAC_pre + BBS_pre + MMSE_pre + first,
  data    = robot,
  method  = "class",
  control = rpart.control(
    cp       = 0.006,  # 복잡도 파라미터, 작게 하면 더 깊은 트리
    maxdepth = 6,     # 트리 최대 깊이
    minsplit = 20     # 분기하기 위한 최소 샘플 수
  )
)

# 트리 시각화
rpart.plot(
  tree_simple,
  type          = 2,        # 깔끔한 박스 스타일
  extra         = 3,        # 노드 안에 클래스별 비율 막대그래프
  under         = TRUE,     # 노드 아래 퍼센트 표시
  box.palette   = "Blues",   # 색상 팔레트
  fallen.leaves = TRUE,      # 리프 노드를 아래에 정렬
  tweak         = 1.2,       # 노드 박스 크기 조정
  cex           = 0.9,       # 글자 크기 조정
  main          = "Decision Tree: Predicting Effector using 4 Predictors"
)

## 'effector'만 추출 후 first 결정
eff_df <- robot %>%
  filter(outcome == "effector") %>%
  droplevels()

# 3) 종속변수·설명변수 확인 및 팩터 변환
#    (first가 이미 팩터라면 생략 가능)
eff_df$first <- as.factor(eff_df$first)

# 4) multiclass CART 모델 학습
tree_eff <- rpart(
  formula = first ~ FMLL_lesion_pre + FAC_pre + BBS_pre + MMSE_pre,
  data    = eff_df,
  method  = "class",
  control = rpart.control(
    cp       = 0.01,   # 복잡도 파라미터 (필요시 조정)
    maxdepth = 5,      # 최대 깊이
    minsplit = 10      # 분기 최소 샘플 수
  )
)

# 5) 트리 시각화 (확률/percent 표시)
prp(tree_eff,
    type          = 1,       # box 안에 split
    extra         = 106,     # 클래스명 + 확률 + percent
    fallen.leaves = TRUE,
    under         = TRUE,    # 노드 아래 percent
    tweak         = 1.2,     # box 크기 조정
    cex           = 0.8,     # 글자 크기
    box.palette   = "Blues",  # multi-class 색상
    main          = "CART: Predicting Robot Modality Among Effectors"
)

# ── Figure 5: CP table ───────────────────────────────────────────────────────
cat("\n=== Figure 5: CP Table (10-fold cross-validation) ===\n")
printcp(tree_eff)

# ── Figure 5: Overfitting assessment ─────────────────────────────────────────
cp5        <- tree_eff$cptable
best5      <- which.min(cp5[, "xerror"])
train_err5 <- min(cp5[, "rel error"])
cv_err5    <- cp5[best5, "xerror"]
xstd5      <- cp5[best5, "xstd"]
diff5      <- cv_err5 - train_err5

cat("\n=== Figure 5: Overfitting Assessment ===\n")
cat(sprintf("  Training error (rel):           %.4f\n", train_err5))
cat(sprintf("  Cross-validated error (xerror): %.4f\n", cv_err5))
cat(sprintf("  Difference:                     %.4f\n", diff5))
cat(sprintf("  xstd at minimum xerror:         %.4f\n", xstd5))
if(diff5 <= xstd5){
  cat("  → Difference ≤ xstd: LIMITED OVERFITTING\n")
} else {
  cat("  → Difference > xstd: MODERATE OVERFITTING — interpret with caution\n")
}

# ── Figure 5: Performance metrics ────────────────────────────────────────────
pred5   <- predict(tree_eff, eff_df, type = "class")
actual5 <- eff_df$first
acc5    <- mean(pred5 == actual5)

cat("\n=== Figure 5: Overall Accuracy ===\n")
cat(sprintf("  Overall Accuracy: %.1f%%\n", acc5*100))
cat("  Note: This model is exploratory; overall accuracy reflects\n")
cat("        class imbalance (LOKOMAT n=244 dominates).\n")

cat("\n=== Figure 5: Per-class Accuracy ===\n")
for(cls in levels(actual5)){
  idx     <- actual5 == cls
  cls_acc <- mean(pred5[idx] == actual5[idx])
  cat(sprintf("  %-15s  n=%3d  accuracy=%.1f%%\n",
              cls, sum(idx), cls_acc*100))
}

cat("\n=== Figure 5: Confusion Matrix ===\n")
print(table(Predicted = pred5, Actual = actual5))

cat("\n=== Figure 5: For manuscript ===\n")
cat(sprintf(
  "The multiclass CART model was constructed as an exploratory analysis\n"))
cat(sprintf(
  "to identify patterns in clinical device assignment among effectors\n"))
cat(sprintf(
  "(n=%d). Overall accuracy was %.1f%%; however, given the class imbalance\n",
  nrow(eff_df), acc5*100))
cat("(LOKOMAT: largest class) and the exploratory rather than predictive\n")
cat("purpose of this model, formal performance metrics should be interpreted\n")
cat("with caution. The CV error was %.4f (training error: %.4f; diff=%.4f),\n")
cat(sprintf(
  "with diff=%.4f exceeding xstd=%.4f, indicating moderate overfitting.\n",
  diff5, xstd5))
cat("External validation is required before clinical application.\n")


total_lok_export <- total %>%
  mutate(
    FAC_pre  = as.numeric(as.character(FAC_pre)),
    sex_bin  = ifelse(sex == "M", 1, 0),
    dx_hem   = ifelse(dx_code == 2, 1, 0)
  ) %>%
  filter(FAC_pre < 5, !is.na(FAC_variation)) %>%
  mutate(
    effector = ifelse(FAC_variation >= 1, 1, 0),
    grp3 = case_when(
      Modality == "NDT"     ~ "NDT",
      Modality == "LOKOMAT" & time_1909 == 0 ~ "Lokomat_pre",
      Modality == "LOKOMAT" & time_1909 == 1 ~ "Lokomat_post",
      TRUE ~ NA_character_
    )
  ) %>%
  filter(!is.na(grp3)) %>%
  mutate(grp3 = factor(grp3, levels = c("NDT", "Lokomat_pre", "Lokomat_post")))

# 저장
write.csv(total_lok_export, "total_lok.csv", row.names = FALSE)

loko_only <- read_csv("lokomat_only.csv")

categorical_vars <- c("group", "sex", "dx_code", "side", "HTN", 
                      "DM", "Dyslipidemia", "A_fib", "time_1809", 
                      "time_1909", "eff")

continuous_vars <- c("age", "bmi", "FMLL_lesion_pre", "FMLL_variation", 
                     "MBI_pre", "MBI_variation", "MMSE_pre", "MMSE_variation",
                     "FAC_variation", "BBS_pre", "BBS_variation", "MRC_pre", 
                     "MRC_variation", "FAC_pre", "Sessions", "Dx_to_Round")

loko_only[categorical_vars] <- lapply(loko_only[categorical_vars], as.factor)

loko_only$FAC_pre <- as.factor(loko_only$FAC_pre)
loko_only$FAC_post <-as.factor(loko_only$FAC_post)
str(loko_only$FAC_pre)  
str(loko_only$FAC_post)

mytable(time_1909~age+sex+bmi+dx_code+side+HTN+DM+Dyslipidemia+A_fib+FMLL_lesion_pre
        +FMLL_variation+MBI_pre+MBI_variation+MMSE_pre+MMSE_variation+FAC_pre
        +FAC_variation+BBS_pre+BBS_variation+MRC_pre+MRC_variation+Sessions+eff, 
        data=loko_only, method=1)
