# ============================================================
# 패키지
# ============================================================
library(haven)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(purrr)
library(tidyr)

# ============================================================
# Step 1 — 데이터 로드
# ============================================================
data_all <- read_sav("E:/Dropbox/STATISTICS/R DATA/NCAST_HOME_short.sav")

ncats_vars <- c("QSNCIA", "QSNCIIA", "QSNCIIIA", "QSNCIVA", "QSNCVA",
                "QSNCVIA", "QSNCMTB", "QSNCBTB", "QSNCMTA",
                "QSNCBTA", "QSNCTTA")

ncats_labels <- c("Sensitivity to Cues",
                  "Response to Distress",
                  "Social-Emotional Fostering",
                  "Cognitive Growth Fostering",
                  "Clarity of Cues",
                  "Responsiveness to Caregiver",
                  "Caregiver Synchrony",
                  "Child Synchrony",
                  "Caregiver Total",
                  "Child Total",
                  "NCATS Total")

home_vars <- c("QSHOMETOTAL", "QSHOMEREP", "QSHOMEACP", "QSHOMEORG",
               "QSHOMELMT",   "QSHOMEIVM", "QSHOMESML")

home_labels <- c("HOME Total",
                 "Responsivity",
                 "Acceptance",
                 "Organization",
                 "Learning Materials",
                 "Involvement",
                 "Variety")

# ============================================================
# Step 2 — 쌍둥이 평균 데이터 생성 (12개월, 24개월)
# ============================================================
make_twin_mean <- function(data, time_val) {
  data %>%
    filter(TIME == time_val) %>%
    group_by(SUBJNO) %>%
    summarise(
      across(all_of(c(ncats_vars, home_vars)), ~ mean(.x, na.rm = TRUE)),
      RAN = first(as.numeric(RAN)),
      .groups = "drop"
    )
}

data_12_mean <- make_twin_mean(data_all, time_val = 0)
data_24_mean <- make_twin_mean(data_all, time_val = 1)

# Pooled: 12개월 + 24개월 평균 (SUBJNO별)
data_pool_mean <- bind_rows(
  data_12_mean %>% mutate(TIME = 0),
  data_24_mean %>% mutate(TIME = 1)
) %>%
  group_by(SUBJNO) %>%
  summarise(
    across(all_of(c(ncats_vars, home_vars)), ~ mean(.x, na.rm = TRUE)),
    RAN = first(RAN),
    .groups = "drop"
  )

# 그룹 분리 (RAN: 1=중재군, 0=대조군)
split_by_ran <- function(df) {
  list(
    INT = filter(df, RAN == 1),
    CON = filter(df, RAN == 0)
  )
}

g_12   <- split_by_ran(data_12_mean)
g_24   <- split_by_ran(data_24_mean)
g_pool <- split_by_ran(data_pool_mean)

cat("샘플 크기 확인\n")
## 샘플 크기 확인
cat("12개월  - 중재:", nrow(g_12$INT),  "| 대조:", nrow(g_12$CON),  "\n")
## 12개월  - 중재: 381 | 대조: 367
cat("24개월  - 중재:", nrow(g_24$INT),  "| 대조:", nrow(g_24$CON),  "\n")
## 24개월  - 중재: 360 | 대조: 359
cat("Pooled  - 중재:", nrow(g_pool$INT),"| 대조:", nrow(g_pool$CON),"\n")
## Pooled  - 중재: 388 | 대조: 375
# ============================================================
# Pooled 샘플 구성 상세 확인
# RAN(중재/대조) × 시점 수(1/2) × 쌍둥이 여부 교차표
# ============================================================

# Step 1: 원자료에서 SUBJNO별 쌍둥이 여부 추출
twin_info <- data_all %>%
  group_by(SUBJNO) %>%
  summarise(
    is_twin  = any(as.numeric(TWIN) == 1),
    n_time   = n_distinct(TIME),          # 참여 시점 수
    RAN      = first(as.numeric(RAN)),
    .groups  = "drop"
  ) %>%
  mutate(
    twin_label = ifelse(is_twin,   "Twin",     "Singleton"),
    time_label = ifelse(n_time == 2, "2 timepoints", "1 timepoint"),
    ran_label  = ifelse(RAN == 1,  "Intervention", "Control")
  )

# Step 2: 교차표 출력
cat("============================================================\n")
## ============================================================
cat("Pooled 샘플 구성: 중재/대조 × 시점 수 × 쌍둥이 여부\n")
## Pooled 샘플 구성: 중재/대조 × 시점 수 × 쌍둥이 여부
cat("============================================================\n\n")
## ============================================================
# 전체 교차표 (3-way)
cross_full <- twin_info %>%
  count(ran_label, time_label, twin_label) %>%
  pivot_wider(names_from = twin_label, values_from = n, values_fill = 0) %>%
  mutate(Subtotal = Singleton + Twin) %>%
  arrange(ran_label, time_label)

print(as.data.frame(cross_full))
##      ran_label   time_label Singleton Twin Subtotal
## 1      Control  1 timepoint        23    1       24
## 2      Control 2 timepoints       332   19      351
## 3 Intervention  1 timepoint        33    2       35
## 4 Intervention 2 timepoints       334   19      353
# Step 3: 그룹별 소계
cat("\n--- 중재군/대조군 소계 ---\n")
## 
## --- 중재군/대조군 소계 ---
ran_summary <- twin_info %>%
  count(ran_label, time_label) %>%
  pivot_wider(names_from = time_label, values_from = n, values_fill = 0) %>%
  mutate(Total = `1 timepoint` + `2 timepoints`)
print(as.data.frame(ran_summary))
##      ran_label 1 timepoint 2 timepoints Total
## 1      Control          24          351   375
## 2 Intervention          35          353   388
cat("\n--- 쌍둥이/싱글톤 소계 ---\n")
## 
## --- 쌍둥이/싱글톤 소계 ---
twin_summary <- twin_info %>%
  count(ran_label, twin_label) %>%
  pivot_wider(names_from = twin_label, values_from = n, values_fill = 0) %>%
  mutate(Total = Singleton + Twin)
print(as.data.frame(twin_summary))
##      ran_label Singleton Twin Total
## 1      Control       355   20   375
## 2 Intervention       367   21   388
cat("\n--- 전체 합계 ---\n")
## 
## --- 전체 합계 ---
cat("총 가족 수(SUBJNO):", nrow(twin_info), "\n")
## 총 가족 수(SUBJNO): 763
cat("  중재군:", sum(twin_info$RAN == 1),
    "| 대조군:", sum(twin_info$RAN == 0), "\n")
##   중재군: 388 | 대조군: 375
cat("  2시점 모두:", sum(twin_info$n_time == 2),
    "| 1시점만:", sum(twin_info$n_time == 1), "\n")
##   2시점 모두: 704 | 1시점만: 59
cat("  Singleton:", sum(!twin_info$is_twin),
    "| Twin 가족:", sum(twin_info$is_twin), "\n")
##   Singleton: 722 | Twin 가족: 41
# Step 4: 보기 좋은 최종 요약표 (논문용)
cat("\n============================================================\n")
## 
## ============================================================
cat("최종 요약표\n")
## 최종 요약표
cat("============================================================\n")
## ============================================================
summary_table <- twin_info %>%
  group_by(ran_label, time_label, twin_label) %>%
  summarise(n = n(), .groups = "drop") %>%
  mutate(label = paste0(ran_label, " / ", time_label, " / ", twin_label)) %>%
  dplyr::select(label, n) %>%
  bind_rows(
    tibble(label = "── TOTAL ──", n = nrow(twin_info))
  )

print(as.data.frame(summary_table))
##                                     label   n
## 1       Control / 1 timepoint / Singleton  23
## 2            Control / 1 timepoint / Twin   1
## 3      Control / 2 timepoints / Singleton 332
## 4           Control / 2 timepoints / Twin  19
## 5  Intervention / 1 timepoint / Singleton  33
## 6       Intervention / 1 timepoint / Twin   2
## 7 Intervention / 2 timepoints / Singleton 334
## 8      Intervention / 2 timepoints / Twin  19
## 9                             ── TOTAL ── 763
# Step 5: 저장
write.csv(cross_full,
          "E:/Dropbox/STATISTICS/R DATA/pooled_sample_breakdown.csv",
          row.names = FALSE)
cat("\n저장 완료: pooled_sample_breakdown.csv\n")
## 
## 저장 완료: pooled_sample_breakdown.csv
# ============================================================
# Step 3 — 함수: 단순 Pearson 상관 (RAN 통제 없음)
# ============================================================

# ── 3a. NCATS-HOME 상관 ──────────────────────────────────
get_cor_table <- function(df) {
  map_dfr(seq_along(ncats_vars), function(i) {
    map_dfr(seq_along(home_vars), function(j) {
      
      df_pair <- df %>%
        dplyr::select(all_of(c(ncats_vars[i], home_vars[j]))) %>%
        filter(complete.cases(.))
      
      ct <- tryCatch(
        cor.test(df_pair[[ncats_vars[i]]], df_pair[[home_vars[j]]],
                 method = "pearson"),
        error = function(e) NULL
      )
      
      if (is.null(ct)) {
        return(data.frame(ncats_label = ncats_labels[i],
                          home_label  = home_labels[j],
                          r = NA, p.value = NA, r_sig = NA))
      }
      
      sig <- ifelse(ct$p.value < .001, "***",
                    ifelse(ct$p.value < .01,  "**",
                           ifelse(ct$p.value < .05,  "*", "")))
      
      data.frame(
        ncats_label = ncats_labels[i],
        home_label  = home_labels[j],
        r           = round(ct$estimate, 3),
        p.value     = ct$p.value,
        n           = nrow(df_pair),
        r_sig       = paste0(sprintf("%.3f", ct$estimate), sig)
      )
    })
  })
}

# ── 3b. NCATS 구독척도 간 상관 ───────────────────────────
get_ncats_cor <- function(df) {
  map_dfr(seq_along(ncats_vars), function(i) {
    map_dfr(seq_along(ncats_vars), function(j) {
      
      if (i >= j) return(NULL)  # 하삼각만
      
      df_pair <- df %>%
        dplyr::select(all_of(c(ncats_vars[i], ncats_vars[j]))) %>%
        filter(complete.cases(.))
      
      ct <- tryCatch(
        cor.test(df_pair[[ncats_vars[i]]], df_pair[[ncats_vars[j]]],
                 method = "pearson"),
        error = function(e) NULL
      )
      
      if (is.null(ct)) {
        return(data.frame(var1 = ncats_labels[i], var2 = ncats_labels[j],
                          r = NA, p.value = NA, r_sig = NA))
      }
      
      sig <- ifelse(ct$p.value < .001, "***",
                    ifelse(ct$p.value < .01,  "**",
                           ifelse(ct$p.value < .05,  "*", "")))
      
      data.frame(
        var1    = ncats_labels[i],
        var2    = ncats_labels[j],
        r       = round(ct$estimate, 3),
        p.value = ct$p.value,
        n       = nrow(df_pair),
        r_sig   = paste0(sprintf("%.3f", ct$estimate), sig)
      )
    })
  })
}

# 행렬 변환
make_matrix <- function(results, labels) {
  mat <- matrix("-", nrow = length(labels), ncol = length(labels))
  rownames(mat) <- labels
  colnames(mat) <- seq_along(labels)
  diag(mat) <- "-"
  for (k in seq_len(nrow(results))) {
    i <- which(labels == results$var1[k])
    j <- which(labels == results$var2[k])
    mat[j, i] <- results$r_sig[k]
  }
  as.data.frame(mat)
}


# ============================================================
# Step 4 — 실행: NCATS-HOME (중재군 / 대조군)
# ============================================================
datasets <- list(
  "12m_INT"   = g_12$INT,
  "12m_CON"   = g_12$CON,
  "24m_INT"   = g_24$INT,
  "24m_CON"   = g_24$CON,
  "Pool_INT"  = g_pool$INT,
  "Pool_CON"  = g_pool$CON
)

results_home_all <- imap(datasets, function(df, label) {
  res <- get_cor_table(df)
  cat("\n=== NCATS-HOME 상관 |", label, "| n =", nrow(df), "===\n")
  wide <- res %>%
    dplyr::select(ncats_label, home_label, r_sig) %>%
    pivot_wider(names_from = home_label, values_from = r_sig)
  print(as.data.frame(wide))
  res
})
## 
## === NCATS-HOME 상관 | 12m_INT | n = 381 ===
##                    ncats_label HOME Total Responsivity Acceptance Organization
## 1          Sensitivity to Cues     0.104*      0.139**      0.027        0.068
## 2         Response to Distress      0.009        0.052     -0.090        0.014
## 3   Social-Emotional Fostering      0.032     0.197***     -0.037       -0.009
## 4   Cognitive Growth Fostering     0.118*     0.195***      0.033        0.075
## 5              Clarity of Cues      0.072        0.080      0.029        0.064
## 6  Responsiveness to Caregiver      0.004        0.037     -0.040        0.091
## 7          Caregiver Synchrony    0.136**     0.243***      0.019        0.083
## 8              Child Synchrony     -0.011        0.031     -0.049        0.082
## 9              Caregiver Total     0.116*     0.241***     -0.007        0.066
## 10                 Child Total      0.030        0.059     -0.020        0.096
## 11                 NCATS Total      0.099     0.204***     -0.015        0.095
##    Learning Materials Involvement Variety
## 1               0.062       0.015  -0.026
## 2              -0.026      -0.022   0.060
## 3              -0.041     -0.131*   0.054
## 4               0.009      -0.030   0.034
## 5              -0.005      -0.004   0.042
## 6              -0.067      -0.047   0.015
## 7              -0.008      -0.074   0.089
## 8              -0.079      -0.049   0.007
## 9               0.004      -0.064   0.046
## 10             -0.055      -0.039   0.028
## 11             -0.024      -0.065   0.047
## 
## === NCATS-HOME 상관 | 12m_CON | n = 367 ===
##                    ncats_label HOME Total Responsivity Acceptance Organization
## 1          Sensitivity to Cues    0.153**     0.196***     0.120*       -0.016
## 2         Response to Distress      0.059        0.030      0.089        0.035
## 3   Social-Emotional Fostering      0.086     0.193***     -0.029        0.046
## 4   Cognitive Growth Fostering   0.177***     0.250***    0.138**        0.026
## 5              Clarity of Cues     0.125*       0.128*     -0.029        0.076
## 6  Responsiveness to Caregiver      0.010        0.036     -0.088        0.007
## 7          Caregiver Synchrony    0.150**     0.244***      0.069        0.022
## 8              Child Synchrony      0.010        0.031     -0.087        0.004
## 9              Caregiver Total   0.197***     0.282***     0.134*        0.034
## 10                 Child Total      0.054        0.074     -0.076        0.033
## 11                 NCATS Total   0.180***     0.256***      0.062        0.044
##    Learning Materials Involvement Variety
## 1               0.053      0.117*   0.009
## 2              -0.005       0.034   0.028
## 3               0.031      -0.005  -0.001
## 4               0.060       0.050   0.034
## 5               0.078       0.023  0.105*
## 6               0.077      -0.029   0.005
## 7               0.041       0.027   0.052
## 8               0.081      -0.027   0.006
## 9               0.061       0.075   0.030
## 10              0.086      -0.013   0.043
## 11              0.093       0.050   0.046
## 
## === NCATS-HOME 상관 | 24m_INT | n = 360 ===
##                    ncats_label HOME Total Responsivity Acceptance Organization
## 1          Sensitivity to Cues      0.071        0.059     -0.050        0.069
## 2         Response to Distress      0.070        0.057      0.056        0.027
## 3   Social-Emotional Fostering      0.006       0.130*     -0.078       -0.014
## 4   Cognitive Growth Fostering     0.119*      0.150**      0.053        0.041
## 5              Clarity of Cues     -0.032        0.018     -0.070       -0.053
## 6  Responsiveness to Caregiver     -0.097       -0.018     -0.097       -0.069
## 7          Caregiver Synchrony      0.103       0.104*      0.023        0.048
## 8              Child Synchrony    -0.113*       -0.030     -0.100       -0.087
## 9              Caregiver Total     0.118*      0.169**      0.007        0.051
## 10                 Child Total     -0.083       -0.006     -0.097       -0.070
## 11                 NCATS Total      0.035       0.119*     -0.054       -0.006
##    Learning Materials Involvement Variety
## 1               0.048       0.052   0.009
## 2               0.058      -0.017   0.034
## 3              -0.038      -0.048   0.020
## 4               0.034      -0.033   0.083
## 5               0.011       0.006  -0.021
## 6               0.003      -0.022  -0.081
## 7               0.044      -0.008   0.076
## 8              -0.003      -0.022  -0.089
## 9               0.042      -0.024   0.069
## 10              0.006      -0.014  -0.068
## 11              0.035      -0.026   0.009
## 
## === NCATS-HOME 상관 | 24m_CON | n = 359 ===
##                    ncats_label HOME Total Responsivity Acceptance Organization
## 1          Sensitivity to Cues      0.076        0.060     0.127*        0.061
## 2         Response to Distress     -0.093        0.026     -0.017     -0.147**
## 3   Social-Emotional Fostering      0.028        0.049      0.039       -0.042
## 4   Cognitive Growth Fostering      0.102        0.084      0.087       -0.016
## 5              Clarity of Cues     0.124*        0.085     -0.004        0.084
## 6  Responsiveness to Caregiver     0.124*        0.041      0.014        0.075
## 7          Caregiver Synchrony      0.018        0.077      0.013       -0.038
## 8              Child Synchrony     0.120*        0.050      0.002        0.067
## 9              Caregiver Total      0.058        0.088      0.093       -0.051
## 10                 Child Total    0.139**        0.062      0.009        0.087
## 11                 NCATS Total     0.131*       0.109*      0.081        0.012
##    Learning Materials Involvement Variety
## 1              -0.015       0.018  -0.009
## 2             -0.119*      -0.050   0.002
## 3               0.004       0.045  -0.025
## 4              -0.003      0.108*   0.019
## 5               0.088      0.124*  -0.030
## 6               0.049      0.108*   0.058
## 7              -0.057       0.038  -0.012
## 8               0.057       0.103   0.053
## 9              -0.043       0.062  -0.000
## 10              0.070      0.127*   0.033
## 11              0.008      0.128*   0.019
## 
## === NCATS-HOME 상관 | Pool_INT | n = 388 ===
##                    ncats_label HOME Total Responsivity Acceptance Organization
## 1          Sensitivity to Cues     0.117*      0.159**     -0.019        0.083
## 2         Response to Distress     0.106*       0.112*      0.008        0.020
## 3   Social-Emotional Fostering      0.030     0.234***     -0.038       -0.061
## 4   Cognitive Growth Fostering    0.150**     0.251***      0.059        0.064
## 5              Clarity of Cues      0.037        0.075     -0.003        0.005
## 6  Responsiveness to Caregiver      0.009        0.059     -0.022        0.002
## 7          Caregiver Synchrony   0.183***     0.283***      0.055        0.079
## 8              Child Synchrony      0.002        0.069     -0.027       -0.008
## 9              Caregiver Total    0.159**     0.298***      0.019        0.048
## 10                 Child Total      0.020        0.072     -0.018        0.003
## 11                 NCATS Total     0.127*     0.256***      0.005        0.037
##    Learning Materials Involvement Variety
## 1               0.075       0.034   0.008
## 2               0.075       0.029   0.072
## 3              -0.033     -0.117*   0.041
## 4               0.074      -0.061   0.054
## 5              -0.006       0.014   0.010
## 6               0.025       0.010  -0.058
## 7               0.051      -0.043  0.106*
## 8               0.012       0.012  -0.070
## 9               0.074      -0.055   0.066
## 10              0.017       0.013  -0.041
## 11              0.063      -0.035   0.028
## 
## === NCATS-HOME 상관 | Pool_CON | n = 375 ===
##                    ncats_label HOME Total Responsivity Acceptance Organization
## 1          Sensitivity to Cues    0.168**     0.186***     0.132*        0.045
## 2         Response to Distress     -0.022        0.080      0.035       -0.087
## 3   Social-Emotional Fostering      0.065      0.154**      0.024        0.006
## 4   Cognitive Growth Fostering   0.218***     0.266***     0.130*        0.054
## 5              Clarity of Cues   0.190***       0.109*      0.025      0.143**
## 6  Responsiveness to Caregiver      0.100        0.097     -0.010        0.069
## 7          Caregiver Synchrony     0.106*     0.233***      0.042       -0.000
## 8              Child Synchrony     0.105*       0.101*     -0.017        0.065
## 9              Caregiver Total   0.191***     0.280***     0.132*        0.024
## 10                 Child Total    0.146**       0.113*      0.002       0.105*
## 11                 NCATS Total   0.225***     0.276***     0.103*        0.073
##    Learning Materials Involvement Variety
## 1               0.040      0.107*   0.034
## 2             -0.106*      -0.030   0.015
## 3               0.011      -0.001   0.000
## 4               0.058      0.128*   0.057
## 5             0.169**      0.122*   0.055
## 6              0.103*       0.031   0.033
## 7              -0.019       0.026   0.031
## 8              0.116*       0.040   0.032
## 9               0.021       0.098   0.047
## 10            0.140**       0.068   0.045
## 11              0.090      0.112*   0.060
# ============================================================
# Step 5 — 실행: NCATS 구독척도 간 상관 (중재군 / 대조군)
# ============================================================
results_ncats_all <- imap(datasets, function(df, label) {
  res <- get_ncats_cor(df)
  mat <- make_matrix(res, ncats_labels)
  cat("\n=== NCATS 구독척도 간 상관 |", label, "| n =", nrow(df), "===\n")
  print(mat)
  list(long = res, matrix = mat)
})
## 
## === NCATS 구독척도 간 상관 | 12m_INT | n = 381 ===
##                                    1        2        3        4        5
## Sensitivity to Cues                -        -        -        -        -
## Response to Distress           0.013        -        -        -        -
## Social-Emotional Fostering  0.274***    0.068        -        -        -
## Cognitive Growth Fostering  0.356***   -0.036 0.411***        -        -
## Clarity of Cues                0.045 -0.150** 0.258*** 0.199***        -
## Responsiveness to Caregiver  0.143**    0.087 0.339*** 0.241*** 0.407***
## Caregiver Synchrony         0.460*** 0.358*** 0.559*** 0.703*** 0.243***
## Child Synchrony               0.114*    0.046 0.327*** 0.229*** 0.434***
## Caregiver Total             0.617*** 0.253*** 0.692*** 0.846*** 0.186***
## Child Total                   0.130*    0.013 0.363*** 0.264*** 0.693***
## NCATS Total                 0.513*** 0.190*** 0.681*** 0.745*** 0.473***
##                                    6        7        8        9       10 11
## Sensitivity to Cues                -        -        -        -        -  -
## Response to Distress               -        -        -        -        -  -
## Social-Emotional Fostering         -        -        -        -        -  -
## Cognitive Growth Fostering         -        -        -        -        -  -
## Clarity of Cues                    -        -        -        -        -  -
## Responsiveness to Caregiver        -        -        -        -        -  -
## Caregiver Synchrony         0.379***        -        -        -        -  -
## Child Synchrony             0.975*** 0.344***        -        -        -  -
## Caregiver Total             0.327*** 0.846*** 0.297***        -        -  -
## Child Total                 0.940*** 0.390*** 0.931*** 0.327***        -  -
## NCATS Total                 0.696*** 0.806*** 0.669*** 0.888*** 0.725***  -
## 
## === NCATS 구독척도 간 상관 | 12m_CON | n = 367 ===
##                                    1        2        3        4        5
## Sensitivity to Cues                -        -        -        -        -
## Response to Distress        0.173***        -        -        -        -
## Social-Emotional Fostering  0.264***   -0.030        -        -        -
## Cognitive Growth Fostering  0.405***   -0.009 0.366***        -        -
## Clarity of Cues                0.041 -0.153**  0.168**    0.085        -
## Responsiveness to Caregiver    0.057   -0.034 0.246***   0.119* 0.554***
## Caregiver Synchrony         0.577*** 0.394*** 0.480*** 0.685***    0.078
## Child Synchrony                0.040   -0.041 0.246***   0.122* 0.573***
## Caregiver Total             0.698*** 0.295*** 0.618*** 0.839***    0.079
## Child Total                    0.058   -0.081 0.246***   0.120* 0.782***
## NCATS Total                 0.566*** 0.182*** 0.606*** 0.708*** 0.481***
##                                    6        7        8        9       10 11
## Sensitivity to Cues                -        -        -        -        -  -
## Response to Distress               -        -        -        -        -  -
## Social-Emotional Fostering         -        -        -        -        -  -
## Cognitive Growth Fostering         -        -        -        -        -  -
## Clarity of Cues                    -        -        -        -        -  -
## Responsiveness to Caregiver        -        -        -        -        -  -
## Caregiver Synchrony          0.160**        -        -        -        -  -
## Child Synchrony             0.980***  0.157**        -        -        -  -
## Caregiver Total              0.160** 0.849***  0.154**        -        -  -
## Child Total                 0.952***  0.148** 0.944***  0.149**        -  -
## NCATS Total                 0.635*** 0.731*** 0.626*** 0.847*** 0.652***  -
## 
## === NCATS 구독척도 간 상관 | 24m_INT | n = 360 ===
##                                    1         2        3        4        5
## Sensitivity to Cues                -         -        -        -        -
## Response to Distress          -0.033         -        -        -        -
## Social-Emotional Fostering  0.326***     0.050        -        -        -
## Cognitive Growth Fostering  0.269***     0.009 0.381***        -        -
## Clarity of Cues               0.131* -0.406*** 0.237***    0.091        -
## Responsiveness to Caregiver 0.216*** -0.193*** 0.239***    0.053 0.598***
## Caregiver Synchrony         0.413***  0.490*** 0.509*** 0.580***  -0.117*
## Child Synchrony              0.155** -0.213*** 0.210***    0.050 0.616***
## Caregiver Total             0.580***  0.364*** 0.682*** 0.790***    0.033
## Child Total                 0.207*** -0.291*** 0.263***    0.073 0.806***
## NCATS Total                 0.551***     0.086 0.660*** 0.621*** 0.521***
##                                    6        7        8        9       10 11
## Sensitivity to Cues                -        -        -        -        -  -
## Response to Distress               -        -        -        -        -  -
## Social-Emotional Fostering         -        -        -        -        -  -
## Cognitive Growth Fostering         -        -        -        -        -  -
## Clarity of Cues                    -        -        -        -        -  -
## Responsiveness to Caregiver        -        -        -        -        -  -
## Caregiver Synchrony           -0.019        -        -        -        -  -
## Child Synchrony             0.979***   -0.049        -        -        -  -
## Caregiver Total               0.114* 0.811***    0.075        -        -  -
## Child Total                 0.956***   -0.057 0.947***    0.096        -  -
## NCATS Total                 0.673*** 0.557*** 0.639*** 0.789*** 0.687***  -
## 
## === NCATS 구독척도 간 상관 | 24m_CON | n = 359 ===
##                                    1         2        3        4         5
## Sensitivity to Cues                -         -        -        -         -
## Response to Distress           0.018         -        -        -         -
## Social-Emotional Fostering  0.335***    0.131*        -        -         -
## Cognitive Growth Fostering  0.406***     0.063 0.417***        -         -
## Clarity of Cues                0.086 -0.530***    0.099    0.066         -
## Responsiveness to Caregiver    0.102 -0.309***   0.132*    0.056  0.530***
## Caregiver Synchrony         0.491***  0.532*** 0.533*** 0.651*** -0.217***
## Child Synchrony                0.054 -0.319***   0.107*    0.041  0.554***
## Caregiver Total             0.642***  0.401*** 0.703*** 0.820***    -0.074
## Child Total                   0.109* -0.428***  0.136**    0.066  0.766***
## NCATS Total                 0.585***     0.066 0.651*** 0.704***  0.404***
##                                    6         7        8        9       10 11
## Sensitivity to Cues                -         -        -        -        -  -
## Response to Distress               -         -        -        -        -  -
## Social-Emotional Fostering         -         -        -        -        -  -
## Cognitive Growth Fostering         -         -        -        -        -  -
## Clarity of Cues                    -         -        -        -        -  -
## Responsiveness to Caregiver        -         -        -        -        -  -
## Caregiver Synchrony         -0.144**         -        -        -        -  -
## Child Synchrony             0.978*** -0.175***        -        -        -  -
## Caregiver Total                0.007  0.847***   -0.027        -        -  -
## Child Total                 0.951*** -0.189*** 0.943***   -0.022        -  -
## NCATS Total                 0.581***  0.571*** 0.550*** 0.796*** 0.588***  -
## 
## === NCATS 구독척도 간 상관 | Pool_INT | n = 388 ===
##                                    1         2        3        4        5
## Sensitivity to Cues                -         -        -        -        -
## Response to Distress           0.092         -        -        -        -
## Social-Emotional Fostering  0.330***     0.098        -        -        -
## Cognitive Growth Fostering  0.387***     0.006 0.452***        -        -
## Clarity of Cues                0.062 -0.283*** 0.311*** 0.200***        -
## Responsiveness to Caregiver 0.222***    -0.006 0.330*** 0.211*** 0.527***
## Caregiver Synchrony         0.509***  0.419*** 0.587*** 0.689***    0.092
## Child Synchrony             0.172***    -0.038 0.310*** 0.194*** 0.538***
## Caregiver Total             0.655***  0.326*** 0.710*** 0.843***  0.160**
## Child Total                 0.192***   -0.106* 0.363*** 0.233*** 0.760***
## NCATS Total                 0.579***  0.188*** 0.705*** 0.738*** 0.497***
##                                    6        7        8        9       10 11
## Sensitivity to Cues                -        -        -        -        -  -
## Response to Distress               -        -        -        -        -  -
## Social-Emotional Fostering         -        -        -        -        -  -
## Cognitive Growth Fostering         -        -        -        -        -  -
## Clarity of Cues                    -        -        -        -        -  -
## Responsiveness to Caregiver        -        -        -        -        -  -
## Caregiver Synchrony         0.259***        -        -        -        -  -
## Child Synchrony             0.977*** 0.215***        -        -        -  -
## Caregiver Total             0.294*** 0.852*** 0.254***        -        -  -
## Child Total                 0.953*** 0.231*** 0.939*** 0.282***        -  -
## NCATS Total                 0.692*** 0.744*** 0.655*** 0.878*** 0.706***  -
## 
## === NCATS 구독척도 간 상관 | Pool_CON | n = 375 ===
##                                    1         2        3        4        5
## Sensitivity to Cues                -         -        -        -        -
## Response to Distress           0.092         -        -        -        -
## Social-Emotional Fostering  0.309***     0.076        -        -        -
## Cognitive Growth Fostering  0.518***    -0.029 0.409***        -        -
## Clarity of Cues                0.079 -0.340*** 0.197***   0.120*        -
## Responsiveness to Caregiver  0.134**  -0.166** 0.241***  0.168** 0.511***
## Caregiver Synchrony         0.577***  0.413*** 0.535*** 0.704***   -0.033
## Child Synchrony                0.098 -0.176*** 0.236***  0.167** 0.536***
## Caregiver Total             0.719***  0.300*** 0.664*** 0.857***    0.064
## Child Total                   0.131* -0.251*** 0.256*** 0.172*** 0.755***
## NCATS Total                 0.625***     0.101 0.649*** 0.754*** 0.447***
##                                    6        7        8        9       10 11
## Sensitivity to Cues                -        -        -        -        -  -
## Response to Distress               -        -        -        -        -  -
## Social-Emotional Fostering         -        -        -        -        -  -
## Cognitive Growth Fostering         -        -        -        -        -  -
## Clarity of Cues                    -        -        -        -        -  -
## Responsiveness to Caregiver        -        -        -        -        -  -
## Caregiver Synchrony            0.090        -        -        -        -  -
## Child Synchrony             0.980***    0.082        -        -        -  -
## Caregiver Total             0.169*** 0.858***  0.154**        -        -  -
## Child Total                 0.949***    0.056 0.944***  0.153**        -  -
## NCATS Total                 0.630*** 0.694*** 0.615*** 0.854*** 0.644***  -
# ============================================================
# Step 6 — 저장
# ============================================================
base_path <- "E:/Dropbox/STATISTICS/R DATA/"

iwalk(results_home_all, function(res, label) {
  # r 값 테이블
  wide_r <- res %>%
    dplyr::select(ncats_label, home_label, r_sig) %>%
    pivot_wider(names_from = home_label, values_from = r_sig)
  write.csv(wide_r,
            paste0(base_path, "HOME_cor_", label, ".csv"),
            row.names = FALSE)
  # 전체 결과 (r, p, n 포함)
  write.csv(res,
            paste0(base_path, "HOME_cor_", label, "_full.csv"),
            row.names = FALSE)
})

iwalk(results_ncats_all, function(res_list, label) {
  write.csv(res_list$matrix,
            paste0(base_path, "NCATS_cor_", label, ".csv"),
            row.names = TRUE)
  write.csv(res_list$long,
            paste0(base_path, "NCATS_cor_", label, "_full.csv"),
            row.names = FALSE)
})

cat("\n모든 파일 저장 완료\n")
## 
## 모든 파일 저장 완료
cat("저장된 파일 목록:\n")
## 저장된 파일 목록:
cat(paste0(" - HOME_cor_", names(datasets), ".csv\n"))
##  - HOME_cor_12m_INT.csv
##   - HOME_cor_12m_CON.csv
##   - HOME_cor_24m_INT.csv
##   - HOME_cor_24m_CON.csv
##   - HOME_cor_Pool_INT.csv
##   - HOME_cor_Pool_CON.csv
cat(paste0(" - NCATS_cor_", names(datasets), ".csv\n"))
##  - NCATS_cor_12m_INT.csv
##   - NCATS_cor_12m_CON.csv
##   - NCATS_cor_24m_INT.csv
##   - NCATS_cor_24m_CON.csv
##   - NCATS_cor_Pool_INT.csv
##   - NCATS_cor_Pool_CON.csv