# ピアソンの相関：散布図＋回帰直線
# sample-data の親フォルダを作業ディレクトリにして実行します。
# 初回だけ必要に応じて実行: install.packages(c("ggplot2", "tidyverse"))

set.seed(20261028)  # 再実行時の乱数を固定
library(tidyverse)

dat <- read.csv("sample-data/sample_pearson_correlation_sleep_fatigue.csv")

dat %>%
  summarise(
    n = n(),
    mean_sleep = mean(sleep_hours),
    sd_sleep = sd(sleep_hours),
    mean_fatigue = mean(fatigue_score),
    sd_fatigue = sd(fatigue_score)
  )

head(dat)

ct <- cor.test(
  dat$sleep_hours,
  dat$fatigue_score,
  method = "pearson"
)

ct

# 相関係数だけを取り出す
cor(dat$sleep_hours, dat$fatigue_score, use = "complete.obs")

library(ggplot2)

ggplot(dat, aes(x = sleep_hours, y = fatigue_score)) +
  geom_point(size = 2.6, alpha = 0.85) +
  geom_smooth(method = "lm", se = FALSE, linewidth = 1.1) +
  labs(
    x = "Sleep hours",
    y = "Fatigue score",
    title = "Relationship between sleep hours and fatigue"
  ) +
  theme_minimal(base_size = 13)

# 外れ値や曲がりの有無を確認するために
# まずは散布図を丁寧に見るのが基本です
