File size: 6,492 Bytes
2394103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
hist_bin_report <- function(x,
                            bin_width = 5,
                            bin_start = NULL,
                            bin_end = NULL,
                            main = "Histogram",
                            xlab = "x",
                            ylab = "Count",
                            col = "blue",
                            density = FALSE) {

  x <- as.numeric(x)
  x <- x[is.finite(x)]
  n <- length(x)
  if (n == 0) stop("x rỗng hoặc không có số hợp lệ.")

  # auto start/end nếu không nhập
  if (is.null(bin_start)) bin_start <- floor(min(x) / bin_width) * bin_width
  if (is.null(bin_end))   bin_end   <- ceiling(max(x) / bin_width) * bin_width
  breaks <- seq(bin_start, bin_end, by = bin_width)

  # --- plot ---
  h <- hist(x, breaks = breaks, right = FALSE, include.lowest = TRUE,
            col = col, border = "white",
            main = main, xlab = xlab, ylab = ylab)

  if (density) {
    d <- density(x)
    # scale density lên cùng trục y (để overlay hợp lý)
    scale_fac <- max(h$counts) / max(d$y)
    lines(d$x, d$y * scale_fac, lwd = 2)
  }

  # --- summary stats ---
  miss <- sum(!is.finite(as.numeric(x)))
  stats <- c(
    n = n,
    miss = miss,
    mean = mean(x),
    sd = sd(x),
    min = min(x),
    mdn = median(x),
    max = max(x)
  )

  # --- outliers theo boxplot ---
  out <- boxplot.stats(x)$out

  # --- bin table giống lessR ---
  lower <- breaks[-length(breaks)]
  upper <- breaks[-1]
  mid   <- (lower + upper) / 2

  bins <- cut(x, breaks = breaks, right = FALSE, include.lowest = TRUE)
  cnt  <- as.integer(table(bins))
  prop <- cnt / n
  cumc <- cumsum(cnt)
  cump <- cumsum(prop)

  tab <- data.frame(
    Bin = paste0(lower, " > ", upper),
    Midpnt = mid,
    Count = cnt,
    Prop = round(prop, 2),
    Cumul.c = cumc,
    Cumul.p = round(cump, 2),
    row.names = NULL
  )

  # In report
  cat("\n--- Summary ---\n")
  print(stats)

  cat("\n--- Outliers (boxplot) ---\n")
  cat("Number of outliers:", length(out), "\n")
  if (length(out)) print(sort(out))

  cat("\n--- Bin table ---\n")
  cat("Bin Width:", bin_width, "\n")
  cat("Number of Bins:", nrow(tab), "\n\n")
  print(tab)

  invisible(list(hist = h, stats = stats, outliers = out, table = tab))
}

two_group_tplot <- function(data, x, group,
                            group_levels = NULL,    # ví dụ c("M","F")
                            var.equal = TRUE,       # "Classic t-test" như hình (df = n1+n2-2) => TRUE
                            conf_level = 0.95,
                            main = "Two-Group Plot with Means",
                            sub = NULL,
                            xlab = NULL,
                            show_box = TRUE) {

  x_name <- deparse(substitute(x))
  g_name <- deparse(substitute(group))

  xv <- data[[x_name]]
  gv <- data[[g_name]]

  ok <- is.finite(as.numeric(xv)) & !is.na(gv)
  xv <- as.numeric(xv[ok])
  gv <- gv[ok]

  gv <- as.character(gv)
  if (!is.null(group_levels)) {
    gv <- factor(gv, levels = group_levels)
  } else {
    gv <- factor(gv)
  }
  if (nlevels(gv) != 2) stop("group phải có đúng 2 nhóm.")

  lev <- levels(gv)
  x1 <- xv[gv == lev[1]]
  x2 <- xv[gv == lev[2]]

  n1 <- length(x1); n2 <- length(x2)
  m1 <- mean(x1);   m2 <- mean(x2)
  s1 <- sd(x1);     s2 <- sd(x2)

  # pooled SD (s-within)
  s_within <- sqrt(((n1 - 1) * s1^2 + (n2 - 1) * s2^2) / (n1 + n2 - 2))
  diff <- m2 - m1
  smd  <- diff / s_within

  # t-test (classic if var.equal=TRUE)
  tt <- t.test(xv ~ gv, var.equal = var.equal, conf.level = conf_level)
  ci <- tt$conf.int
  tval <- unname(tt$statistic)
  df   <- unname(tt$parameter)
  pval <- unname(tt$p.value)

  # densities
  d1 <- density(x1)
  d2 <- density(x2)

  xlim <- range(c(d1$x, d2$x))
  ylim <- c(0, max(d1$y, d2$y) * 1.15)

  if (is.null(sub)) sub <- sprintf("Compare %s for %s %s and %s", x_name, g_name, lev[2], lev[1])
  if (is.null(xlab)) xlab <- x_name

  oldpar <- par(no.readonly = TRUE)
  on.exit(par(oldpar), add = TRUE)

  par(mar = c(5, 4, 7, 2))  # chừa chỗ tiêu đề phía trên

  plot(NA, xlim = xlim, ylim = ylim, xlab = xlab, ylab = "", main = "", axes = TRUE)

  # fill colors (nhẹ như hình)
  col1_fill <- adjustcolor("#4C72B0", alpha.f = 0.18)  # xanh
  col2_fill <- adjustcolor("#C49A3A", alpha.f = 0.18)  # vàng nâu
  col1_line <- "#4C72B0"
  col2_line <- "#C49A3A"

  polygon(d1$x, d1$y, col = col1_fill, border = NA)
  polygon(d2$x, d2$y, col = col2_fill, border = NA)
  lines(d1$x, d1$y, col = col1_line, lwd = 2)
  lines(d2$x, d2$y, col = col2_line, lwd = 2)

  # mean lines
  abline(v = m1, col = adjustcolor(col1_line, 0.45), lwd = 1.5)
  abline(v = m2, col = adjustcolor(col2_line, 0.45), lwd = 1.5)

  # bottom bracket for mean diff
  yb <- ylim[2] * 0.10
  segments(m1, yb, m2, yb, col = "grey40", lwd = 2)
  segments(m1, yb*0.92, m1, yb*1.08, col = "grey40", lwd = 2)
  segments(m2, yb*0.92, m2, yb*1.08, col = "grey40", lwd = 2)
  text((m1 + m2)/2, yb*1.12, sprintf("%.3f\ndiff", diff), col = "grey35")

  # top axis in standardized units (0,1,2) where 0 at mean of group1
  axis_at <- m1 + s_within * c(0, 1, 2)
  axis(3, at = axis_at, labels = c("0","1","2"), tck = -0.02, col = "grey40", col.axis = "grey25")

  # top bracket showing SMD
  yt <- ylim[2] * 0.92
  segments(m1, yt, m2, yt, col = "grey55", lwd = 2)
  text((m1 + m2)/2, yt*1.03, sprintf("%.3f\nsmd", smd), col = "grey35")
  text(m1 + s_within, ylim[2] * 0.98, sprintf("s-within\n%.2f", s_within), col = "grey40")

  # side text blocks like lessR
  if (show_box) {
    text(xlim[1] + diff(xlim)*0.02, ylim[2]*0.86,
         sprintf("%s %s\nn = %d\nm = %.3f\ns = %.3f", g_name, lev[1], n1, m1, s1),
         adj = c(0, 1))
    text(xlim[2] - diff(xlim)*0.02, ylim[2]*0.86,
         sprintf("%s %s\nn = %d\nm = %.3f\ns = %.3f", g_name, lev[2], n2, m2, s2),
         adj = c(1, 1))
  }

  # header text (giống hình)
  title(main = main, sub = sub, line = 4)
  mtext(sprintf("Classic t-test of 0 Mean Diff:   t = %.3f,  df = %.0f,  p-value = %.3f",
                tval, df, pval),
        side = 3, line = 2, cex = 1.05)
  mtext(sprintf("%d%% Confidence Interval for Mean Difference:  %.3f to %.3f",
                round(conf_level*100), ci[1], ci[2]),
        side = 3, line = 1, cex = 1.05)

  invisible(list(
    group_levels = lev,
    n = c(n1, n2),
    mean = c(m1, m2),
    sd = c(s1, s2),
    diff = diff,
    s_within = s_within,
    smd = smd,
    ttest = tt
  ))
}