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 )) }