Nothing
#' Create a Summary Table for a One-Sample t-test
#'
#' @param t_res An object of class "htest" produced by \code{t.test()},or a list of such objects.
#' @param variable_label A character string to label the tested variable(s).
#' @param digits Integer indicating the number of decimal places to round to.
#'
#' @return A data frame summarizing the one-sample t-test results.
#'
#' @examples
#' data("attitude")
#' A <- as.data.frame(attitude)
#'
#' # Example 1: One-sample t-test with default mu = 0
#' t1 <- t.test(A$rating)
#' make_one_sample_t_test_table(
#' t_res = t1,
#' variable_label = "Rating"
#' )
#'
#' # Example 2: One-sample t-test with specified mu
#' t2 <- t.test(A$rating, mu = 60)
#' make_one_sample_t_test_table(
#' t_res = t2,
#' variable_label = "Rating"
#' )
#'
#' # Example 3: Multiple one-sample t-tests combined into one table
#' t1 <- t.test(A$rating)
#' t2 <- t.test(A$learning)
#' t3 <- t.test(A$raises)
#'
#' make_one_sample_t_test_table(
#' t_res = list(t1, t2, t3),
#' variable_label = c("Rating", "Learning", "Raises")
#' )
#'
#' # Example 4: Multiple tests with different mu values
#' t1 <- t.test(A$rating, mu = 60)
#' t2 <- t.test(A$learning, mu = 65)
#' t3 <- t.test(A$raises, mu = 50)
#'
#' make_one_sample_t_test_table(
#' t_res = list(t1, t2, t3),
#' variable_label = c("Rating", "Learning", "Raises (mu = 50)")
#' )
#' @export
make_one_sample_t_test_table <- function(t_res, variable_label = "Variable", digits = 3) {
# 1 Allow single htest or list of htest
if(inherits(t_res,"htest")){
t_res <- list(t_res)
}
# 2. Validate the input
if (!all(sapply(t_res,inherits,"htest" ))) {
stop("All inputs must be an 'htest' object generated by t.test()")
}
# 3. the label are equal number as htest object
n_tests <- length(t_res)
if (length(variable_label) == 1) {
variable_label <- rep(variable_label, n_tests)
}
if (length(variable_label) != n_tests) {
stop("Length of variable_label must match number of tests")
}
# 4. Extract and format the statistics into a data frame
results <- lapply(seq_along(t_res), function(i) {
test <- t_res[[i]]
# format p value
p_formatted <- ifelse(test$p.value < 10^-digits,
paste0("< ", formatC(10^-digits, format = "f", digits = digits)),
formatC(test$p.value, format = "f", digits = digits))
data.frame(
Variable = variable_label[i],
Sample_Mean = round(as.numeric(test$estimate), digits),
Test_Value = round(as.numeric(test$null.value), digits),
t_statistic = round(as.numeric(test$statistic), digits),
df = as.numeric(test$parameter),
p_value = p_formatted,
CI_lower = round(as.numeric(test$conf.int[1]), digits),
CI_upper = round(as.numeric(test$conf.int[2]), digits),
stringsAsFactors = FALSE
)
})
# bind all result in a table
df <- do.call(rbind, results)
rownames(df) <- NULL
return(df)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.