diff --git a/.Rbuildignore b/.Rbuildignore index 475a5231..ab82a293 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -52,3 +52,4 @@ references.bib ^revdep$ ^CRAN-SUBMISSION$ ^LICENSE\.md$ +^[.]?air[.]toml$ diff --git a/R/cor_lower.R b/R/cor_lower.R index d1b9ecac..6a6a801e 100644 --- a/R/cor_lower.R +++ b/R/cor_lower.R @@ -45,7 +45,10 @@ cor_lower.easycorrelation <- function(x, diag = FALSE, ...) { for (param1 in rownames(m)) { for (param2 in colnames(m)) { if (tri[param1, param2]) { - tokeep <- c(tokeep, which(x$Parameter1 == param1 & x$Parameter2 == param2)) + tokeep <- c( + tokeep, + which(x$Parameter1 == param1 & x$Parameter2 == param2) + ) } } } diff --git a/R/cor_smooth.R b/R/cor_smooth.R index 0399de79..8e7cda3b 100644 --- a/R/cor_smooth.R +++ b/R/cor_smooth.R @@ -30,47 +30,66 @@ cor_smooth <- function(x, method = "psych", verbose = TRUE, ...) { #' @export -cor_smooth.easycorrelation <- function(x, - method = "psych", - verbose = TRUE, - tol = 10^-12, - ...) { - m <- cor_smooth(as.matrix(x), method = method, verbose = verbose, tol = tol, ...) +cor_smooth.easycorrelation <- function( + x, + method = "psych", + verbose = TRUE, + tol = 10^-12, + ... +) { + m <- cor_smooth( + as.matrix(x), + method = method, + verbose = verbose, + tol = tol, + ... + ) if (isTRUE(attributes(m)$smoothed)) { estim <- names(x)[names(x) %in% c("r", "rho", "tau", "D")][1] for (param1 in row.names(m)) { for (param2 in colnames(m)) { - if (nrow(x[x$Parameter1 == param1 & x$Parameter2 == param2, ]) == 0) next + if (nrow(x[x$Parameter1 == param1 & x$Parameter2 == param2, ]) == 0) { + next + } # Print changes if (verbose) { val1 <- x[x$Parameter1 == param1 & x$Parameter2 == param2, estim] val2 <- m[param1, param2] if (round(val1 - val2, digits = 2) == 0) { - insight::print_color(paste0( - param1, - " - ", - param2, - ": no change (", - insight::format_value(val1), - ")\n" - ), "green") + insight::print_color( + paste0( + param1, + " - ", + param2, + ": no change (", + insight::format_value(val1), + ")\n" + ), + "green" + ) } else { - insight::print_color(paste0( - param1, - " - ", - param2, - ": ", - insight::format_value(val1), - " -> ", - insight::format_value(val2), - "\n" - ), "red") + insight::print_color( + paste0( + param1, + " - ", + param2, + ": ", + insight::format_value(val1), + " -> ", + insight::format_value(val2), + "\n" + ), + "red" + ) } cat("\n") } - x[x$Parameter1 == param1 & x$Parameter2 == param2, estim] <- m[param1, param2] + x[x$Parameter1 == param1 & x$Parameter2 == param2, estim] <- m[ + param1, + param2 + ] } } @@ -87,16 +106,20 @@ cor_smooth.easycorrelation <- function(x, #' @export -cor_smooth.matrix <- function(x, - method = "psych", - verbose = TRUE, - tol = 10^-12, - ...) { +cor_smooth.matrix <- function( + x, + method = "psych", + verbose = TRUE, + tol = 10^-12, + ... +) { method <- match.arg(method, choices = c("psych", "hj", "lrs")) # Already positive definite if (is.positive_definite(x, tol = tol, ...)) { - if (verbose) message("Matrix is positive definite, smoothing was not needed.") + if (verbose) { + message("Matrix is positive definite, smoothing was not needed.") + } return(x) } @@ -104,7 +127,10 @@ cor_smooth.matrix <- function(x, insight::check_if_installed("psych") x <- suppressWarnings(psych::cor.smooth(x, eig.tol = tol, ...)) } else { - out <- try(suppressMessages(mbend::bend(x, method = method, ...)), silent = TRUE) + out <- try( + suppressMessages(mbend::bend(x, method = method, ...)), + silent = TRUE + ) if (inherits(out, "try-error")) { return(x) } @@ -134,9 +160,12 @@ is.positive_definite.matrix <- function(x, tol = 10^-12, ...) { # validation checks if (inherits(eigens, "try-error")) { - stop(insight::format_message( - "There is something seriously wrong with the correlation matrix, as some of the eigen values are NA." - ), call. = FALSE) + stop( + insight::format_message( + "There is something seriously wrong with the correlation matrix, as some of the eigen values are NA." + ), + call. = FALSE + ) } # Find out diff --git a/R/cor_sort.R b/R/cor_sort.R index 554464e6..d0ef8471 100644 --- a/R/cor_sort.R +++ b/R/cor_sort.R @@ -20,13 +20,28 @@ #' cor_sort(x, hclust_method = "ward.D2") # It can also reorder the long form output #' cor_sort(summary(x, redundant = TRUE)) # As well as from the summary #' @export -cor_sort <- function(x, distance = "correlation", hclust_method = "complete", ...) { +cor_sort <- function( + x, + distance = "correlation", + hclust_method = "complete", + ... +) { UseMethod("cor_sort") } #' @export -cor_sort.easycorrelation <- function(x, distance = "correlation", hclust_method = "complete", ...) { - m <- cor_sort(as.matrix(x), distance = distance, hclust_method = hclust_method, ...) +cor_sort.easycorrelation <- function( + x, + distance = "correlation", + hclust_method = "complete", + ... +) { + m <- cor_sort( + as.matrix(x), + distance = distance, + hclust_method = hclust_method, + ... + ) x$Parameter1 <- factor(x$Parameter1, levels = rownames(m)) x$Parameter2 <- factor(x$Parameter2, levels = colnames(m)) reordered <- x[order(x$Parameter1, x$Parameter2), ] @@ -48,7 +63,12 @@ cor_sort.easycorrelation <- function(x, distance = "correlation", hclust_method #' @export -cor_sort.easycormatrix <- function(x, distance = "correlation", hclust_method = "complete", ...) { +cor_sort.easycormatrix <- function( + x, + distance = "correlation", + hclust_method = "complete", + ... +) { if (!"Parameter" %in% colnames(x)) { return(NextMethod()) } @@ -60,7 +80,9 @@ cor_sort.easycormatrix <- function(x, distance = "correlation", hclust_method = # If non-redundant matrix, fail (## TODO: fix that) if (anyNA(m)) { - insight::format_error("Non-redundant matrices are not supported yet. Try again by setting summary(..., redundant = TRUE)") + insight::format_error( + "Non-redundant matrices are not supported yet. Try again by setting summary(..., redundant = TRUE)" + ) } # Get sorted matrix @@ -77,9 +99,22 @@ cor_sort.easycormatrix <- function(x, distance = "correlation", hclust_method = ) # Reorder attributes (p-values) etc. - for (id in c("p", "CI", "CI_low", "CI_high", "BF", "Method", "n_Obs", "df_error", "t")) { + for (id in c( + "p", + "CI", + "CI_low", + "CI_high", + "BF", + "Method", + "n_Obs", + "df_error", + "t" + )) { if (id %in% names(attributes(reordered))) { - attributes(reordered)[[id]] <- attributes(reordered)[[id]][order(x$Parameter), names(reordered)] + attributes(reordered)[[id]] <- attributes(reordered)[[id]][ + order(x$Parameter), + names(reordered) + ] } } @@ -91,9 +126,19 @@ cor_sort.easycormatrix <- function(x, distance = "correlation", hclust_method = #' @export -cor_sort.matrix <- function(x, distance = "correlation", hclust_method = "complete", ...) { +cor_sort.matrix <- function( + x, + distance = "correlation", + hclust_method = "complete", + ... +) { if (isSquare(x) && all(colnames(x) %in% rownames(x))) { - i <- .cor_sort_square(x, distance = distance, hclust_method = hclust_method, ...) + i <- .cor_sort_square( + x, + distance = distance, + hclust_method = hclust_method, + ... + ) } else { i <- .cor_sort_nonsquare(x, distance = "euclidean", ...) } @@ -111,8 +156,12 @@ cor_sort.matrix <- function(x, distance = "correlation", hclust_method = "comple # Utils ------------------------------------------------------------------- - -.cor_sort_square <- function(m, distance = "correlation", hclust_method = "complete", ...) { +.cor_sort_square <- function( + m, + distance = "correlation", + hclust_method = "complete", + ... +) { if (distance == "correlation") { d <- stats::as.dist((1 - m) / 2) # r = -1 -> d = 1; r = 1 -> d = 0 } else if (distance == "raw") { diff --git a/R/cor_test.R b/R/cor_test.R index 1eae95ad..2f53914c 100644 --- a/R/cor_test.R +++ b/R/cor_test.R @@ -118,38 +118,53 @@ #' } #' } #' @export -cor_test <- function(data, - x, - y, - method = "pearson", - ci = 0.95, - bayesian = FALSE, - bayesian_prior = "medium", - bayesian_ci_method = "hdi", - bayesian_test = c("pd", "rope", "bf"), - include_factors = FALSE, - partial = FALSE, - partial_bayesian = FALSE, - multilevel = FALSE, - ranktransform = FALSE, - winsorize = FALSE, - verbose = TRUE, - ...) { +cor_test <- function( + data, + x, + y, + method = "pearson", + ci = 0.95, + bayesian = FALSE, + bayesian_prior = "medium", + bayesian_ci_method = "hdi", + bayesian_test = c("pd", "rope", "bf"), + include_factors = FALSE, + partial = FALSE, + partial_bayesian = FALSE, + multilevel = FALSE, + ranktransform = FALSE, + winsorize = FALSE, + verbose = TRUE, + ... +) { # valid matrix checks if (!all(x %in% names(data)) || !all(y %in% names(data))) { - insight::format_error("The names you entered for x and y are not available in the dataset. Make sure there are no typos!") + insight::format_error( + "The names you entered for x and y are not available in the dataset. Make sure there are no typos!" + ) } - if (ci == "default") ci <- 0.95 - if (!partial && (partial_bayesian || multilevel)) partial <- TRUE + if (ci == "default") { + ci <- 0.95 + } + if (!partial && (partial_bayesian || multilevel)) { + partial <- TRUE + } # Make sure factor is no factor if (!method %in% c("tetra", "tetrachoric", "poly", "polychoric")) { - data[c(x, y)] <- datawizard::to_numeric(data[c(x, y)], dummy_factors = FALSE) + data[c(x, y)] <- datawizard::to_numeric( + data[c(x, y)], + dummy_factors = FALSE + ) } # However, for poly, we need factors! - if (method %in% c("poly", "polychoric") && all(vapply(data[c(x, y)], is.numeric, FUN.VALUE = TRUE))) { + if ( + method %in% + c("poly", "polychoric") && + all(vapply(data[c(x, y)], is.numeric, FUN.VALUE = TRUE)) + ) { # convert all input to factors, but only if all input currently is numeric # we allow mix of numeric and factors data[c(x, y)] <- datawizard::to_factor(data[c(x, y)]) @@ -159,13 +174,23 @@ cor_test <- function(data, if (!isFALSE(partial)) { # partial if (isTRUE(partial)) { - data[[x]] <- datawizard::adjust(data[names(data) != y], multilevel = multilevel, bayesian = partial_bayesian)[[x]] - data[[y]] <- datawizard::adjust(data[names(data) != x], multilevel = multilevel, bayesian = partial_bayesian)[[y]] + data[[x]] <- datawizard::adjust( + data[names(data) != y], + multilevel = multilevel, + bayesian = partial_bayesian + )[[x]] + data[[y]] <- datawizard::adjust( + data[names(data) != x], + multilevel = multilevel, + bayesian = partial_bayesian + )[[y]] } # semi-partial if (partial == "semi") { - insight::format_error("Semi-partial correlations are not supported yet. Get in touch if you want to contribute.") + insight::format_error( + "Semi-partial correlations are not supported yet. Get in touch if you want to contribute." + ) } } @@ -178,7 +203,8 @@ cor_test <- function(data, # winsorization would otherwise fail in case of NAs present data <- as.data.frame( - datawizard::winsorize(stats::na.omit(data[c(x, y)]), + datawizard::winsorize( + stats::na.omit(data[c(x, y)]), threshold = winsorize, verbose = verbose ) @@ -187,7 +213,11 @@ cor_test <- function(data, # Rank transform (i.e., "robust") if (ranktransform) { - data[c(x, y)] <- datawizard::ranktransform(data[c(x, y)], sign = FALSE, method = "average") + data[c(x, y)] <- datawizard::ranktransform( + data[c(x, y)], + sign = FALSE, + method = "average" + ) } # check if enough no. of obs ------------------------------ @@ -197,7 +227,12 @@ cor_test <- function(data, invalid <- FALSE if (n_obs < 3L) { if (isTRUE(verbose)) { - insight::format_warning(paste(x, "and", y, "have less than 3 complete observations. Returning NA.")) + insight::format_warning(paste( + x, + "and", + y, + "have less than 3 complete observations. Returning NA." + )) } invalid <- TRUE original_info <- list(data = data, x = x, y = y) @@ -206,11 +241,14 @@ cor_test <- function(data, y <- "disp" } - # Find method method <- tolower(method) - if (method == "auto" && !bayesian) method <- .find_correlationtype(data, x, y) - if (method == "auto" && bayesian) method <- "pearson" + if (method == "auto" && !bayesian) { + method <- .find_correlationtype(data, x, y) + } + if (method == "auto" && bayesian) { + method <- "pearson" + } # Frequentist if (!bayesian) { @@ -224,7 +262,9 @@ cor_test <- function(data, out <- .cor_test_biweight(data, x, y, ci = ci, ...) } else if (method == "distance") { out <- .cor_test_distance(data, x, y, ci = ci, ...) - } else if (method %in% c("percentage", "percentage_bend", "percentagebend", "pb")) { + } else if ( + method %in% c("percentage", "percentage_bend", "percentagebend", "pb") + ) { out <- .cor_test_percentage(data, x, y, ci = ci, ...) } else if (method %in% c("blomqvist", "median", "medial")) { out <- .cor_test_blomqvist(data, x, y, ci = ci, ...) @@ -244,23 +284,43 @@ cor_test <- function(data, # Bayesian } else if (method %in% c("tetra", "tetrachoric")) { - insight::format_error("Tetrachoric Bayesian correlations are not supported yet. Get in touch if you want to contribute.") + insight::format_error( + "Tetrachoric Bayesian correlations are not supported yet. Get in touch if you want to contribute." + ) } else if (method %in% c("poly", "polychoric")) { - insight::format_error("Polychoric Bayesian correlations are not supported yet. Get in touch if you want to contribute.") + insight::format_error( + "Polychoric Bayesian correlations are not supported yet. Get in touch if you want to contribute." + ) } else if (method %in% c("biserial", "pointbiserial", "point-biserial")) { - insight::format_error("Biserial Bayesian correlations are not supported yet. Get in touch if you want to contribute.") + insight::format_error( + "Biserial Bayesian correlations are not supported yet. Get in touch if you want to contribute." + ) } else if (method == "biweight") { - insight::format_error("Biweight Bayesian correlations are not supported yet. Get in touch if you want to contribute.") + insight::format_error( + "Biweight Bayesian correlations are not supported yet. Get in touch if you want to contribute." + ) } else if (method == "distance") { - insight::format_error("Bayesian distance correlations are not supported yet. Get in touch if you want to contribute.") - } else if (method %in% c("percentage", "percentage_bend", "percentagebend", "pb")) { - insight::format_error("Bayesian Percentage Bend correlations are not supported yet. Get in touch if you want to contribute.") + insight::format_error( + "Bayesian distance correlations are not supported yet. Get in touch if you want to contribute." + ) + } else if ( + method %in% c("percentage", "percentage_bend", "percentagebend", "pb") + ) { + insight::format_error( + "Bayesian Percentage Bend correlations are not supported yet. Get in touch if you want to contribute." + ) } else if (method %in% c("blomqvist", "median", "medial")) { - insight::format_error("Bayesian Blomqvist correlations are not supported yet. Check-out the BBcor package (https://github.com/donaldRwilliams/BBcor).") + insight::format_error( + "Bayesian Blomqvist correlations are not supported yet. Check-out the BBcor package (https://github.com/donaldRwilliams/BBcor)." + ) } else if (method == "hoeffding") { - insight::format_error("Bayesian Hoeffding's correlations are not supported yet. Check-out the BBcor package (https://github.com/donaldRwilliams/BBcor).") + insight::format_error( + "Bayesian Hoeffding's correlations are not supported yet. Check-out the BBcor package (https://github.com/donaldRwilliams/BBcor)." + ) } else if (method == "gamma") { - insight::format_error("Bayesian gamma correlations are not supported yet. Get in touch if you want to contribute.") + insight::format_error( + "Bayesian gamma correlations are not supported yet. Get in touch if you want to contribute." + ) } else if (method %in% c("shepherd", "sheperd", "shepherdspi", "pi")) { out <- .cor_test_shepherd(data, x, y, ci = ci, bayesian = TRUE, ...) } else { @@ -291,7 +351,17 @@ cor_test <- function(data, # Reorder columns if ("CI_low" %in% names(out)) { - col_order <- c("Parameter1", "Parameter2", "r", "rho", "tau", "Dxy", "CI", "CI_low", "CI_high") + col_order <- c( + "Parameter1", + "Parameter2", + "r", + "rho", + "tau", + "Dxy", + "CI", + "CI_low", + "CI_high" + ) out <- out[c( col_order[col_order %in% names(out)], setdiff(colnames(out), col_order[col_order %in% names(out)]) @@ -299,17 +369,23 @@ cor_test <- function(data, } # Output - attr(out, "coefficient_name") <- c("rho", "r", "tau", "Dxy")[c("rho", "r", "tau", "Dxy") %in% names(out)][1] + attr(out, "coefficient_name") <- c("rho", "r", "tau", "Dxy")[ + c("rho", "r", "tau", "Dxy") %in% names(out) + ][1] attr(out, "ci") <- ci attr(out, "data") <- data - class(out) <- unique(c("easycor_test", "easycorrelation", "parameters_model", class(out))) + class(out) <- unique(c( + "easycor_test", + "easycorrelation", + "parameters_model", + class(out) + )) out } # Utilities --------------------------------------------------------------- - #' @keywords internal .complete_variable_x <- function(data, x, y) { data[[x]][stats::complete.cases(data[[x]], data[[y]])] diff --git a/R/cor_test_bayes.R b/R/cor_test_bayes.R index e9acaa5c..e45430fc 100644 --- a/R/cor_test_bayes.R +++ b/R/cor_test_bayes.R @@ -1,13 +1,15 @@ #' @keywords internal -.cor_test_bayes <- function(data, - x, - y, - ci = 0.95, - method = "pearson", - bayesian_prior = "medium", - bayesian_ci_method = "hdi", - bayesian_test = c("pd", "rope", "bf"), - ...) { +.cor_test_bayes <- function( + data, + x, + y, + ci = 0.95, + method = "pearson", + bayesian_prior = "medium", + bayesian_ci_method = "hdi", + bayesian_test = c("pd", "rope", "bf"), + ... +) { insight::check_if_installed("BayesFactor") var_x <- .complete_variable_x(data, x, y) @@ -44,16 +46,18 @@ #' @keywords internal -.cor_test_bayes_base <- function(x, - y, - var_x, - var_y, - ci = 0.95, - bayesian_prior = "medium", - bayesian_ci_method = "hdi", - bayesian_test = c("pd", "rope", "bf"), - method = "pearson", - ...) { +.cor_test_bayes_base <- function( + x, + y, + var_x, + var_y, + ci = 0.95, + bayesian_prior = "medium", + bayesian_ci_method = "hdi", + bayesian_test = c("pd", "rope", "bf"), + method = "pearson", + ... +) { insight::check_if_installed("BayesFactor") if (x == y) { @@ -72,15 +76,33 @@ rope_ci = 1, ... ) - if ("Median" %in% names(params)) params$Median <- 1 - if ("Mean" %in% names(params)) params$Mean <- 1 - if ("MAP" %in% names(params)) params$MAP <- 1 - if ("SD" %in% names(params)) params$SD <- 0 - if ("MAD" %in% names(params)) params$MAD <- 0 - if ("CI_low" %in% names(params)) params$CI_low <- 1 - if ("CI_high" %in% names(params)) params$CI_high <- 1 - if ("pd" %in% names(params)) params$pd <- 1 - if ("ROPE_Percentage" %in% names(params)) params$ROPE_Percentage <- 0 + if ("Median" %in% names(params)) { + params$Median <- 1 + } + if ("Mean" %in% names(params)) { + params$Mean <- 1 + } + if ("MAP" %in% names(params)) { + params$MAP <- 1 + } + if ("SD" %in% names(params)) { + params$SD <- 0 + } + if ("MAD" %in% names(params)) { + params$MAD <- 0 + } + if ("CI_low" %in% names(params)) { + params$CI_low <- 1 + } + if ("CI_high" %in% names(params)) { + params$CI_high <- 1 + } + if ("pd" %in% names(params)) { + params$pd <- 1 + } + if ("ROPE_Percentage" %in% names(params)) { + params$ROPE_Percentage <- 0 + } if ("BF" %in% names(params)) params$BF <- Inf } else { rez <- suppressWarnings(BayesFactor::correlationBF( diff --git a/R/cor_test_biserial.R b/R/cor_test_biserial.R index 0a874205..5d97bb7b 100644 --- a/R/cor_test_biserial.R +++ b/R/cor_test_biserial.R @@ -1,5 +1,12 @@ #' @keywords internal -.cor_test_biserial <- function(data, x, y, ci = 0.95, method = "biserial", ...) { +.cor_test_biserial <- function( + data, + x, + y, + ci = 0.95, + method = "biserial", + ... +) { # valid matrix if (.vartype(data[[x]])$is_binary && !.vartype(data[[y]])$is_binary) { binary <- x @@ -14,7 +21,9 @@ } # Rescale to 0-1 - if (.vartype(data[[binary]])$is_factor || .vartype(data[[binary]])$is_character) { + if ( + .vartype(data[[binary]])$is_factor || .vartype(data[[binary]])$is_character + ) { data[[binary]] <- as.numeric(as.factor(data[[binary]])) } @@ -27,7 +36,15 @@ if (method == "biserial") { out <- .cor_test_biserial_biserial(data, x, y, continuous, binary, ci) } else { - out <- .cor_test_biserial_pointbiserial(data, x, y, continuous, binary, ci, ...) + out <- .cor_test_biserial_pointbiserial( + data, + x, + y, + continuous, + binary, + ci, + ... + ) } out @@ -35,8 +52,23 @@ #' @keywords internal -.cor_test_biserial_pointbiserial <- function(data, x, y, continuous, binary, ci, ...) { - out <- .cor_test_freq(data, continuous, binary, ci = ci, method = "pearson", ...) +.cor_test_biserial_pointbiserial <- function( + data, + x, + y, + continuous, + binary, + ci, + ... +) { + out <- .cor_test_freq( + data, + continuous, + binary, + ci = ci, + method = "pearson", + ... + ) names(out)[names(out) == "r"] <- "rho" out$Parameter1 <- x out$Parameter2 <- y @@ -51,7 +83,6 @@ var_x <- .complete_variable_x(data, continuous, binary) var_y <- .complete_variable_y(data, continuous, binary) - m1 <- mean(var_x[var_y == 1]) m0 <- mean(var_x[var_y == 0]) quan <- mean(var_y) diff --git a/R/cor_test_biweight.R b/R/cor_test_biweight.R index c2f18ef5..e85fb415 100644 --- a/R/cor_test_biweight.R +++ b/R/cor_test_biweight.R @@ -3,7 +3,6 @@ var_x <- .complete_variable_x(data, x, y) var_y <- .complete_variable_y(data, x, y) - # https://github.com/easystats/correlation/issues/13 u <- (var_x - stats::median(var_x)) / (9 * stats::mad(var_x, constant = 1)) v <- (var_y - stats::median(var_y)) / (9 * stats::mad(var_y, constant = 1)) @@ -14,7 +13,6 @@ w_x <- I_x * (1 - u^2)^2 w_y <- I_y * (1 - v^2)^2 - denominator_x <- sqrt(sum(((var_x - stats::median(var_x)) * w_x)^2)) x_curly <- ((var_x - stats::median(var_x)) * w_x) / denominator_x diff --git a/R/cor_test_distance.R b/R/cor_test_distance.R index 88e8ba25..41d7080a 100644 --- a/R/cor_test_distance.R +++ b/R/cor_test_distance.R @@ -39,7 +39,6 @@ # Basis ------------------------------------------------------------------- - #' @keywords internal .cor_test_distance_corrected <- function(x, y, ci = 0.95) { x <- as.matrix(stats::dist(x)) @@ -102,7 +101,6 @@ # Utils ------------------------------------------------------------------- - #' @keywords internal .A_kl <- function(x, index) { d <- as.matrix(x)^index @@ -121,7 +119,9 @@ ## denoted A* (or B*) in JMVA t-test paper (2013) d <- as.matrix(d) n <- nrow(d) - if (n != ncol(d)) stop("Argument d should be distance", call. = FALSE) + if (n != ncol(d)) { + stop("Argument d should be distance", call. = FALSE) + } m <- rowMeans(d) M <- mean(d) a <- sweep(d, 1, m) diff --git a/R/cor_test_freq.R b/R/cor_test_freq.R index 68a00aa8..4a7da17f 100644 --- a/R/cor_test_freq.R +++ b/R/cor_test_freq.R @@ -8,9 +8,28 @@ #' @keywords internal -.cor_test_base <- function(x, y, var_x, var_y, ci = 0.95, method = "pearson", ...) { - method <- match.arg(tolower(method), c("pearson", "kendall", "spearman", "somers"), several.ok = FALSE) - rez <- stats::cor.test(var_x, var_y, conf.level = ci, method = method, exact = FALSE, ...) +.cor_test_base <- function( + x, + y, + var_x, + var_y, + ci = 0.95, + method = "pearson", + ... +) { + method <- match.arg( + tolower(method), + c("pearson", "kendall", "spearman", "somers"), + several.ok = FALSE + ) + rez <- stats::cor.test( + var_x, + var_y, + conf.level = ci, + method = method, + exact = FALSE, + ... + ) # params <- parameters::model_parameters(rez) # this doubles performance according to computation time @@ -20,21 +39,35 @@ params$Parameter2 <- y if (x == y) { - if ("t" %in% names(params)) params$t <- Inf - if ("z" %in% names(params)) params$z <- Inf + if ("t" %in% names(params)) { + params$t <- Inf + } + if ("z" %in% names(params)) { + params$z <- Inf + } if ("S" %in% names(params)) params$S <- Inf } # Add CI for non-pearson correlations if (method %in% c("kendall", "spearman")) { - rez_ci <- cor_to_ci(rez$estimate, n = length(var_x), ci = ci, method = method, ...) + rez_ci <- cor_to_ci( + rez$estimate, + n = length(var_x), + ci = ci, + method = method, + ... + ) params$CI_low <- rez_ci$CI_low params$CI_high <- rez_ci$CI_high } # see ?cor.test: CI only in case of at least 4 complete pairs of observations - if (!("CI_low" %in% names(params))) params$CI_low <- NA - if (!("CI_high" %in% names(params))) params$CI_high <- NA + if (!("CI_low" %in% names(params))) { + params$CI_low <- NA + } + if (!("CI_high" %in% names(params))) { + params$CI_high <- NA + } params } diff --git a/R/cor_test_gamma.R b/R/cor_test_gamma.R index 31273ee5..ab3cfe61 100644 --- a/R/cor_test_gamma.R +++ b/R/cor_test_gamma.R @@ -13,7 +13,6 @@ p <- cor_to_p(r, n = length(var_x)) ci_vals <- cor_to_ci(r, n = length(var_x), ci = ci) - data.frame( Parameter1 = x, Parameter2 = y, diff --git a/R/cor_test_polychoric.R b/R/cor_test_polychoric.R index 16411008..bb81540a 100644 --- a/R/cor_test_polychoric.R +++ b/R/cor_test_polychoric.R @@ -7,10 +7,11 @@ # valid matrix check if (!is.factor(var_x) && !is.factor(var_y)) { - insight::format_error("Polychoric correlations can only be ran on ordinal factors.") + insight::format_error( + "Polychoric correlations can only be ran on ordinal factors." + ) } - if (!is.factor(var_x) || !is.factor(var_y)) { insight::check_if_installed("polycor", "for 'polyserial' correlations") diff --git a/R/cor_test_shepherd.R b/R/cor_test_shepherd.R index 363540af..736630c9 100644 --- a/R/cor_test_shepherd.R +++ b/R/cor_test_shepherd.R @@ -8,10 +8,20 @@ if (bayesian) { data <- data[not_outliers, ] - data[c(x, y)] <- datawizard::ranktransform(data[c(x, y)], sign = TRUE, method = "average") + data[c(x, y)] <- datawizard::ranktransform( + data[c(x, y)], + sign = TRUE, + method = "average" + ) out <- .cor_test_bayes(data, x, y, ci = ci) } else { - out <- .cor_test_freq(data[not_outliers, ], x, y, ci = ci, method = "spearman") + out <- .cor_test_freq( + data[not_outliers, ], + x, + y, + ci = ci, + method = "spearman" + ) } out$Method <- "Shepherd's Pi" out diff --git a/R/cor_test_tetrachoric.R b/R/cor_test_tetrachoric.R index df776683..8429f9ef 100644 --- a/R/cor_test_tetrachoric.R +++ b/R/cor_test_tetrachoric.R @@ -7,7 +7,9 @@ # valid matrix check if (length(unique(var_x)) > 2 && length(unique(var_y)) > 2) { - insight::format_error("Tetrachoric correlations can only be ran on dichotomous data.") + insight::format_error( + "Tetrachoric correlations can only be ran on dichotomous data." + ) } # Reconstruct dataframe diff --git a/R/cor_text.R b/R/cor_text.R index 35cf269e..cdc56b28 100644 --- a/R/cor_text.R +++ b/R/cor_text.R @@ -16,11 +16,21 @@ #' #' cor_text(rez) #' @export -cor_text <- function(x, show_ci = TRUE, show_statistic = TRUE, show_sig = TRUE, ...) { +cor_text <- function( + x, + show_ci = TRUE, + show_statistic = TRUE, + show_sig = TRUE, + ... +) { # Estimate candidates <- c("rho", "r", "tau", "Difference", "r_rank_biserial") estimate <- candidates[candidates %in% names(x)][1] - out_text <- paste0(tolower(estimate), " = ", insight::format_value(x[[estimate]])) + out_text <- paste0( + tolower(estimate), + " = ", + insight::format_value(x[[estimate]]) + ) # CI if (show_ci && all(c("CI_high", "CI_low") %in% names(x))) { @@ -29,7 +39,11 @@ cor_text <- function(x, show_ci = TRUE, show_statistic = TRUE, show_sig = TRUE, out_text <- paste0( out_text, ", ", - insight::format_ci(x$CI_low, x$CI_high, ci = attributes(x$conf.int)$conf.level) + insight::format_ci( + x$CI_low, + x$CI_high, + ci = attributes(x$conf.int)$conf.level + ) ) } else if ("CI" %in% names(x)) { # param @@ -72,11 +86,21 @@ cor_text <- function(x, show_ci = TRUE, show_statistic = TRUE, show_sig = TRUE, # Significance if (show_sig) { if ("p" %in% names(x)) { - out_text <- paste0(out_text, ", ", insight::format_p(x$p, digits = "apa", ...)) + out_text <- paste0( + out_text, + ", ", + insight::format_p(x$p, digits = "apa", ...) + ) } else if ("BF" %in% names(x)) { exact <- match.call()[["exact"]] - if (is.null(exact)) exact <- TRUE - out_text <- paste0(out_text, ", ", insight::format_bf(x$BF, exact = exact, ...)) + if (is.null(exact)) { + exact <- TRUE + } + out_text <- paste0( + out_text, + ", ", + insight::format_bf(x$BF, exact = exact, ...) + ) } else if ("pd" %in% names(x)) { out_text <- paste0(out_text, ", ", insight::format_pd(x$pd, ...)) } diff --git a/R/cor_to_ci.R b/R/cor_to_ci.R index ce9c88e9..707ad705 100644 --- a/R/cor_to_ci.R +++ b/R/cor_to_ci.R @@ -5,8 +5,19 @@ #' better, though the Bishara and Hittner (2017) paper favours the Fieller #' correction. Both are generally very similar. #' @export -cor_to_ci <- function(cor, n, ci = 0.95, method = "pearson", correction = "fieller", ...) { - method <- match.arg(tolower(method), c("pearson", "kendall", "spearman"), several.ok = FALSE) +cor_to_ci <- function( + cor, + n, + ci = 0.95, + method = "pearson", + correction = "fieller", + ... +) { + method <- match.arg( + tolower(method), + c("pearson", "kendall", "spearman"), + several.ok = FALSE + ) if (method == "kendall") { out <- .cor_to_ci_kendall(cor, n, ci = ci, correction = correction, ...) @@ -43,7 +54,13 @@ cor_to_ci <- function(cor, n, ci = 0.95, method = "pearson", correction = "fiell # Spearman ----------------------------------------------------------------- -.cor_to_ci_spearman <- function(cor, n, ci = 0.95, correction = "fieller", ...) { +.cor_to_ci_spearman <- function( + cor, + n, + ci = 0.95, + correction = "fieller", + ... +) { # by @tsbaguley (https://rpubs.com/seriousstats/616206) if (correction == "fieller") { diff --git a/R/cor_to_cov.R b/R/cor_to_cov.R index 9ba75ff7..6d137f82 100644 --- a/R/cor_to_cov.R +++ b/R/cor_to_cov.R @@ -13,7 +13,12 @@ #' cor_to_cov(cor, sd = sapply(iris[1:4], sd)) #' cor_to_cov(cor, variance = sapply(iris[1:4], var)) #' @export -cor_to_cov <- function(cor, sd = NULL, variance = NULL, tol = .Machine$double.eps^(2 / 3)) { +cor_to_cov <- function( + cor, + sd = NULL, + variance = NULL, + tol = .Machine$double.eps^(2 / 3) +) { # valid matrix checks if (!isSquare(cor)) { insight::format_error("The matrix should be a square matrix.") @@ -30,11 +35,15 @@ cor_to_cov <- function(cor, sd = NULL, variance = NULL, tol = .Machine$double.ep n <- nrow(cor) if (n != length(sd)) { - insight::format_error("The length of 'sd' or 'variance' should be the same as the number of rows of the matrix.") + insight::format_error( + "The length of 'sd' or 'variance' should be the same as the number of rows of the matrix." + ) } if (length(sd[sd > 0]) != n) { - insight::format_error("The elements in 'sd' or 'variance' should all be non-negative.") + insight::format_error( + "The elements in 'sd' or 'variance' should all be non-negative." + ) } if (isSymmetric(cor)) { @@ -44,13 +53,18 @@ cor_to_cov <- function(cor, sd = NULL, variance = NULL, tol = .Machine$double.ep } p <- dim(cor)[1] quan <- p * (p - 1) / 2 - if (isTRUE(all.equal(cor[lower.tri(cor)], rep(0, quan))) || isTRUE(all.equal(cor[upper.tri(cor)], rep(0, quan)))) { + if ( + isTRUE(all.equal(cor[lower.tri(cor)], rep(0, quan))) || + isTRUE(all.equal(cor[upper.tri(cor)], rep(0, quan))) + ) { is_triangular <- TRUE } else { is_triangular <- FALSE } if (!is_symmetric && !is_triangular) { - insight::format_error("'cor' should be either a symmetric or a triangular matrix") + insight::format_error( + "'cor' should be either a symmetric or a triangular matrix" + ) } cov_matrix <- diag(sd) %*% cor %*% diag(sd) diff --git a/R/cor_to_pcor.R b/R/cor_to_pcor.R index ff9e7a14..17ea6b83 100644 --- a/R/cor_to_pcor.R +++ b/R/cor_to_pcor.R @@ -62,14 +62,16 @@ cor_to_pcor.easycormatrix <- function(cor, tol = .Machine$double.eps^(2 / 3)) { #' @export -cor_to_pcor.easycorrelation <- function(cor, tol = .Machine$double.eps^(2 / 3)) { +cor_to_pcor.easycorrelation <- function( + cor, + tol = .Machine$double.eps^(2 / 3) +) { .cor_to_pcor_easycorrelation(cor = cor, tol = tol) } # pcor to cor ------------------------------------------------------------- - #' @rdname cor_to_pcor #' @export pcor_to_cor <- function(pcor, tol = .Machine$double.eps^(2 / 3)) { @@ -95,7 +97,10 @@ pcor_to_cor.easycormatrix <- function(pcor, tol = .Machine$double.eps^(2 / 3)) { #' @export -pcor_to_cor.easycorrelation <- function(pcor, tol = .Machine$double.eps^(2 / 3)) { +pcor_to_cor.easycorrelation <- function( + pcor, + tol = .Machine$double.eps^(2 / 3) +) { .cor_to_pcor_easycorrelation(pcor = pcor, tol = tol) } @@ -103,7 +108,11 @@ pcor_to_cor.easycorrelation <- function(pcor, tol = .Machine$double.eps^(2 / 3)) # Convenience Functions -------------------------------------------------------- #' @keywords internal -.cor_to_pcor_easycorrelation <- function(pcor = NULL, cor = NULL, tol = .Machine$double.eps^(2 / 3)) { +.cor_to_pcor_easycorrelation <- function( + pcor = NULL, + cor = NULL, + tol = .Machine$double.eps^(2 / 3) +) { if (is.null(cor)) { r <- .pcor_to_cor(.get_cor(summary(pcor, redundant = TRUE), cov = NULL)) cor <- pcor @@ -155,7 +164,7 @@ pcor_to_cor.easycorrelation <- function(pcor, tol = .Machine$double.eps^(2 / 3)) # Format newdata <- cbind(cor[1:2], newdata) cor <- cor[, seq_len(ncol(newdata))] - cor[, ] <- newdata + cor[,] <- newdata names(cor) <- names(newdata) # P-values adjustments @@ -167,7 +176,11 @@ pcor_to_cor.easycorrelation <- function(pcor, tol = .Machine$double.eps^(2 / 3)) #' @keywords internal -.cor_to_pcor_easycormatrix <- function(pcor = NULL, cor = NULL, tol = .Machine$double.eps^(2 / 3)) { +.cor_to_pcor_easycormatrix <- function( + pcor = NULL, + cor = NULL, + tol = .Machine$double.eps^(2 / 3) +) { if (is.null(cor)) { r <- .pcor_to_cor(.get_cor(pcor, cov = NULL)) cor <- pcor @@ -190,8 +203,16 @@ pcor_to_cor.easycorrelation <- function(pcor, tol = .Machine$double.eps^(2 / 3)) # P-values adjustments n_comp <- sum(upper.tri(p$p)) - p$p[upper.tri(p$p)] <- stats::p.adjust(p$p[upper.tri(p$p)], method = p_adjust, n = n_comp) - p$p[lower.tri(p$p)] <- stats::p.adjust(p$p[lower.tri(p$p)], method = p_adjust, n = n_comp) + p$p[upper.tri(p$p)] <- stats::p.adjust( + p$p[upper.tri(p$p)], + method = p_adjust, + n = n_comp + ) + p$p[lower.tri(p$p)] <- stats::p.adjust( + p$p[lower.tri(p$p)], + method = p_adjust, + n = n_comp + ) attributes(cor)$p_adjust <- p_adjust # Statistic and p-value @@ -243,7 +264,9 @@ pcor_to_cor.easycorrelation <- function(pcor, tol = .Machine$double.eps^(2 / 3)) insight::format_error("A correlation or covariance matrix is required.") } cor <- stats::cov2cor(cov) - } else if (inherits(cor, "easycormatrix") && colnames(cor)[1] == "Parameter") { + } else if ( + inherits(cor, "easycormatrix") && colnames(cor)[1] == "Parameter" + ) { row.names(cor) <- cor$Parameter cor <- as.matrix(cor[-1]) } diff --git a/R/cor_to_spcor.R b/R/cor_to_spcor.R index a43fb90b..b474b70b 100644 --- a/R/cor_to_spcor.R +++ b/R/cor_to_spcor.R @@ -1,17 +1,25 @@ #' @rdname cor_to_pcor #' @export -cor_to_spcor <- function(cor = NULL, cov = NULL, tol = .Machine$double.eps^(2 / 3)) { +cor_to_spcor <- function( + cor = NULL, + cov = NULL, + tol = .Machine$double.eps^(2 / 3) +) { cor <- .get_cor(cor, cov) # Semi-partial if (is.null(cov)) { - insight::format_error("Covariance matrix (or vector of SD of variables) needs to be passed for semi-partial correlations.") + insight::format_error( + "Covariance matrix (or vector of SD of variables) needs to be passed for semi-partial correlations." + ) } else { if (!is.matrix(cov)) { cov <- cor_to_cov(cor, sd = cov) } inverted <- .invert_matrix(cov, tol = tol) - out <- -stats::cov2cor(inverted) / sqrt(diag(cov)) / sqrt(abs(diag(inverted) - t(t(inverted^2) / diag(inverted)))) + out <- -stats::cov2cor(inverted) / + sqrt(diag(cov)) / + sqrt(abs(diag(inverted) - t(t(inverted^2) / diag(inverted)))) } diag(out) <- 1 diff --git a/R/cormatrix_to_excel.R b/R/cormatrix_to_excel.R index a4448ef3..75694d5c 100644 --- a/R/cormatrix_to_excel.R +++ b/R/cormatrix_to_excel.R @@ -41,13 +41,17 @@ #' \dontshow{ #' setwd(.old_wd) #' } -cormatrix_to_excel <- function(data, - filename, - overwrite = TRUE, - print.mat = TRUE, - ...) { +cormatrix_to_excel <- function( + data, + filename, + overwrite = TRUE, + print.mat = TRUE, + ... +) { if (missing(filename)) { - insight::format_error("Argument 'filename' required (as per CRAN policies).") + insight::format_error( + "Argument 'filename' required (as per CRAN policies)." + ) } insight::check_if_installed("openxlsx2") @@ -409,7 +413,8 @@ cormatrix_to_excel <- function(data, # Save Excel cat(paste0( - "\n\n [Correlation matrix '", filename, + "\n\n [Correlation matrix '", + filename, ".xlsx' has been saved to working directory (or where specified).]" )) openxlsx2::wb_save(wb, file = paste0(filename, ".xlsx"), overwrite = TRUE) diff --git a/R/correlation.R b/R/correlation.R index 33288778..d9f4de87 100644 --- a/R/correlation.R +++ b/R/correlation.R @@ -247,29 +247,31 @@ #' ordinal variables. American Sociological Review. 27 (6). #' #' @export -correlation <- function(data, - data2 = NULL, - select = NULL, - select2 = NULL, - rename = NULL, - method = "pearson", - missing = "keep_pairwise", - p_adjust = "holm", - ci = 0.95, - bayesian = FALSE, - bayesian_prior = "medium", - bayesian_ci_method = "hdi", - bayesian_test = c("pd", "rope", "bf"), - redundant = FALSE, - include_factors = FALSE, - partial = FALSE, - partial_bayesian = FALSE, - multilevel = FALSE, - ranktransform = FALSE, - winsorize = FALSE, - verbose = TRUE, - standardize_names = getOption("easystats.standardize_names", FALSE), - ...) { +correlation <- function( + data, + data2 = NULL, + select = NULL, + select2 = NULL, + rename = NULL, + method = "pearson", + missing = "keep_pairwise", + p_adjust = "holm", + ci = 0.95, + bayesian = FALSE, + bayesian_prior = "medium", + bayesian_ci_method = "hdi", + bayesian_test = c("pd", "rope", "bf"), + redundant = FALSE, + include_factors = FALSE, + partial = FALSE, + partial_bayesian = FALSE, + multilevel = FALSE, + ranktransform = FALSE, + winsorize = FALSE, + verbose = TRUE, + standardize_names = getOption("easystats.standardize_names", FALSE), + ... +) { # valid matrix checks if (!partial && multilevel) { partial <- TRUE @@ -294,7 +296,11 @@ correlation <- function(data, not_in_data <- !all_selected %in% colnames(data) if (any(not_in_data)) { insight::format_error( - paste0("Following variables are not in the data: ", all_selected[not_in_data], collapse = ", ") + paste0( + "Following variables are not in the data: ", + all_selected[not_in_data], + collapse = ", " + ) ) } @@ -308,7 +314,6 @@ correlation <- function(data, grp_df <- NULL } - data2 <- if (!is.null(select2)) data[select2] data <- data[select] @@ -325,7 +330,10 @@ correlation <- function(data, } } - missing <- insight::validate_argument(missing, options = c("keep_pairwise", "keep_complete")) + missing <- insight::validate_argument( + missing, + options = c("keep_pairwise", "keep_complete") + ) if (missing == "keep_complete") { if (is.null(data2)) { oo <- stats::complete.cases(data) @@ -405,37 +413,54 @@ correlation <- function(data, attr(out, "additional_arguments") <- list(...) if (inherits(data, "grouped_df")) { - class(out) <- unique(c("easycorrelation", "see_easycorrelation", "grouped_easycorrelation", "parameters_model", class(out))) + class(out) <- unique(c( + "easycorrelation", + "see_easycorrelation", + "grouped_easycorrelation", + "parameters_model", + class(out) + )) } else { - class(out) <- unique(c("easycorrelation", "see_easycorrelation", "parameters_model", class(out))) + class(out) <- unique(c( + "easycorrelation", + "see_easycorrelation", + "parameters_model", + class(out) + )) } - if (convert_back_to_r) out <- pcor_to_cor(pcor = out) # Revert back to r if needed. + if (convert_back_to_r) { + out <- pcor_to_cor(pcor = out) + } # Revert back to r if needed. - if (standardize_names) insight::standardize_names(out, ...) + if (standardize_names) { + insight::standardize_names(out, ...) + } out } #' @keywords internal -.correlation_grouped_df <- function(data, - data2 = NULL, - method = "pearson", - p_adjust = "holm", - ci = "default", - bayesian = FALSE, - bayesian_prior = "medium", - bayesian_ci_method = "hdi", - bayesian_test = c("pd", "rope", "bf"), - redundant = FALSE, - include_factors = TRUE, - partial = FALSE, - partial_bayesian = FALSE, - multilevel = FALSE, - ranktransform = FALSE, - winsorize = FALSE, - verbose = TRUE, - ...) { +.correlation_grouped_df <- function( + data, + data2 = NULL, + method = "pearson", + p_adjust = "holm", + ci = "default", + bayesian = FALSE, + bayesian_prior = "medium", + bayesian_ci_method = "hdi", + bayesian_test = c("pd", "rope", "bf"), + redundant = FALSE, + include_factors = TRUE, + partial = FALSE, + partial_bayesian = FALSE, + multilevel = FALSE, + ranktransform = FALSE, + winsorize = FALSE, + verbose = TRUE, + ... +) { groups <- setdiff(colnames(attributes(data)$groups), ".rows") ungrouped_x <- as.data.frame(data) xlist <- split(ungrouped_x, ungrouped_x[groups], sep = " - ") @@ -473,7 +498,9 @@ correlation <- function(data, if (inherits(data2, "grouped_df")) { groups2 <- setdiff(colnames(attributes(data2)$groups), ".rows") if (!all.equal(groups, groups2)) { - insight::format_error("'data2' should have the same grouping characteristics as data.") + insight::format_error( + "'data2' should have the same grouping characteristics as data." + ) } ungrouped_y <- as.data.frame(data2) ylist <- split(ungrouped_y, ungrouped_y[groups], sep = " - ") @@ -515,31 +542,35 @@ correlation <- function(data, #' @keywords internal -.correlation <- function(data, - data2 = NULL, - method = "pearson", - p_adjust = "holm", - ci = "default", - bayesian = FALSE, - bayesian_prior = "medium", - bayesian_ci_method = "hdi", - bayesian_test = c("pd", "rope", "bf"), - redundant = FALSE, - include_factors = FALSE, - partial = FALSE, - partial_bayesian = FALSE, - multilevel = FALSE, - ranktransform = FALSE, - winsorize = FALSE, - verbose = TRUE, - ...) { +.correlation <- function( + data, + data2 = NULL, + method = "pearson", + p_adjust = "holm", + ci = "default", + bayesian = FALSE, + bayesian_prior = "medium", + bayesian_ci_method = "hdi", + bayesian_test = c("pd", "rope", "bf"), + redundant = FALSE, + include_factors = FALSE, + partial = FALSE, + partial_bayesian = FALSE, + multilevel = FALSE, + ranktransform = FALSE, + winsorize = FALSE, + verbose = TRUE, + ... +) { if (!is.null(data2)) { data <- cbind(data, data2) } if (ncol(data) <= 2L && any(sapply(data, is.factor)) && !include_factors) { if (isTRUE(verbose)) { - insight::format_warning("It seems like there is not enough continuous variables in your data. Maybe you want to include the factors? We're setting `include_factors=TRUE` for you.") + insight::format_warning( + "It seems like there is not enough continuous variables in your data. Maybe you want to include the factors? We're setting `include_factors=TRUE` for you." + ) } include_factors <- TRUE } @@ -547,7 +578,10 @@ correlation <- function(data, # valid matrix checks ---------------- # What if only factors - if (sum(sapply(if (is.null(data2)) data else cbind(data, data2), is.numeric)) == 0) { + if ( + sum(sapply(if (is.null(data2)) data else cbind(data, data2), is.numeric)) == + 0 + ) { include_factors <- TRUE } @@ -571,7 +605,11 @@ correlation <- function(data, multilevel = multilevel, method = method ) - data <- .clean_data(data, include_factors = include_factors, multilevel = multilevel) + data <- .clean_data( + data, + include_factors = include_factors, + multilevel = multilevel + ) # LOOP ---------------- @@ -613,7 +651,9 @@ correlation <- function(data, if ("r" %in% names(result) && !"r" %in% names(params)) { names(params)[names(params) %in% c("rho", "tau")] <- "r" } - if (!"r" %in% names(params) && any(c("rho", "tau") %in% names(result))) { + if ( + !"r" %in% names(params) && any(c("rho", "tau") %in% names(result)) + ) { names(params)[names(params) %in% c("rho", "tau")] <- "r" names(result)[names(result) %in% c("rho", "tau")] <- "r" } diff --git a/R/display.R b/R/display.R index 986fc3ea..bc9eec04 100644 --- a/R/display.R +++ b/R/display.R @@ -30,13 +30,15 @@ #' s <- summary(corr) #' display(s) #' @export -display.easycormatrix <- function(object, - format = "markdown", - digits = 2, - p_digits = 3, - stars = TRUE, - include_significance = NULL, - ...) { +display.easycormatrix <- function( + object, + format = "markdown", + digits = 2, + p_digits = 3, + stars = TRUE, + include_significance = NULL, + ... +) { if (format == "markdown") { print_md( x = object, @@ -60,12 +62,14 @@ display.easycormatrix <- function(object, #' @export -display.easycorrelation <- function(object, - format = "markdown", - digits = 2, - p_digits = 3, - stars = TRUE, - ...) { +display.easycorrelation <- function( + object, + format = "markdown", + digits = 2, + p_digits = 3, + stars = TRUE, + ... +) { if (format == "markdown") { print_md( x = object, diff --git a/R/methods.easycorrelation.R b/R/methods.easycorrelation.R index 22c2f17c..1198fd70 100644 --- a/R/methods.easycorrelation.R +++ b/R/methods.easycorrelation.R @@ -2,10 +2,12 @@ # @examples # summary(correlation(mtcars), target = "p") #' @export -summary.easycorrelation <- function(object, - redundant = FALSE, - target = NULL, - ...) { +summary.easycorrelation <- function( + object, + redundant = FALSE, + target = NULL, + ... +) { # If data2 is present if (!is.null(attributes(object)$data2)) { redundant <- FALSE @@ -19,36 +21,63 @@ summary.easycorrelation <- function(object, } if (is.null(target)) { - target <- names(object)[names(object) %in% c("r", "rho", "tau", "Median", "Dxy")][1] + target <- names(object)[ + names(object) %in% c("r", "rho", "tau", "Median", "Dxy") + ][1] if (is.na(target)) { - target <- names(object)[!names(object) %in% c("Parameter1", "Parameter2")][1] + target <- names(object)[ + !names(object) %in% c("Parameter1", "Parameter2") + ][1] } } else { target <- target[target %in% names(object)][1] if (is.na(target) || length(target) == 0) { - stop("`target` must be a column name in the correlation object.", call. = FALSE) + stop( + "`target` must be a column name in the correlation object.", + call. = FALSE + ) } } - out <- .create_matrix(cormatrix, object, column = target, redundant = redundant) + out <- .create_matrix( + cormatrix, + object, + column = target, + redundant = redundant + ) # Fill attributes - for (i in names(object)[!names(object) %in% c("Group", "Parameter1", "Parameter2", target)]) { - attri <- .create_matrix(cormatrix, object, column = i, redundant = redundant) + for (i in names(object)[ + !names(object) %in% c("Group", "Parameter1", "Parameter2", target) + ]) { + attri <- .create_matrix( + cormatrix, + object, + column = i, + redundant = redundant + ) attr(out, i) <- attri } # Transfer attributes attributes(out) <- c( attributes(out), - attributes(object)[!names(attributes(object)) %in% c("names", "row.names", "class", names(attributes(out)))] + attributes(object)[ + !names(attributes(object)) %in% + c("names", "row.names", "class", names(attributes(out))) + ] ) attributes(out) <- c(attributes(out), list(...)) attr(out, "redundant") <- redundant attr(out, "coefficient_name") <- target if (inherits(object, "grouped_easycorrelation")) { - class(out) <- c("easycormatrix", "see_easycormatrix", "grouped_easycormatrix", class(out)) + class(out) <- c( + "easycormatrix", + "see_easycormatrix", + "grouped_easycormatrix", + class(out) + ) } else { class(out) <- c("easycormatrix", "see_easycormatrix", class(out)) } @@ -120,7 +149,15 @@ as.list.easycorrelation <- function(x, cols = NULL, redundant = FALSE, ...) { #' @export standardize_names.easycorrelation <- function(data, ...) { ori <- data - names(data)[names(data) == datawizard::extract_column_names(data, select = "(rho|tau)", regex = TRUE, verbose = FALSE)] <- "r" + names(data)[ + names(data) == + datawizard::extract_column_names( + data, + select = "(rho|tau)", + regex = TRUE, + verbose = FALSE + ) + ] <- "r" data <- insight::standardize_names(as.data.frame(data), ...) class(data) <- class(ori) data @@ -152,7 +189,11 @@ standardize_names.easycorrelation <- function(data, ...) { .fill_matrix <- function(frame, object, column = "r", redundant = TRUE) { for (row in row.names(frame)) { for (col in colnames(frame)) { - frame[row, col] <- object[(object$Parameter1 == row & object$Parameter2 == col) | (object$Parameter2 == row & object$Parameter1 == col), column][1] + frame[row, col] <- object[ + (object$Parameter1 == row & object$Parameter2 == col) | + (object$Parameter2 == row & object$Parameter1 == col), + column + ][1] } } @@ -179,7 +220,9 @@ standardize_names.easycorrelation <- function(data, ...) { } if (is.null(cols)) { - cols <- colnames(object)[!colnames(object) %in% c("Group", "Parameter1", "Parameter2")] + cols <- colnames(object)[ + !colnames(object) %in% c("Group", "Parameter1", "Parameter2") + ] } sx <- summary(object = object, redundant = redundant, ...) @@ -204,7 +247,10 @@ standardize_names.easycorrelation <- function(data, ...) { attributes(lx) <- c( attributes(lx), class = "easymatrixlist", - attributes(sx)[!names(attributes(sx)) %in% c("names", "row.names", "class", "coefficient_name", names(lx))] + attributes(sx)[ + !names(attributes(sx)) %in% + c("names", "row.names", "class", "coefficient_name", names(lx)) + ] ) lx diff --git a/R/methods_format.R b/R/methods_format.R index acf80d20..a839bcc7 100644 --- a/R/methods_format.R +++ b/R/methods_format.R @@ -1,12 +1,14 @@ # Correlation table --------------------------------------------------------- #' @export -format.easycorrelation <- function(x, - digits = NULL, - p_digits = NULL, - stars = NULL, - format = NULL, - ...) { +format.easycorrelation <- function( + x, + digits = NULL, + p_digits = NULL, + stars = NULL, + format = NULL, + ... +) { if (nrow(x) == 0) { warning("The table is empty, no rows left to print.", call. = FALSE) return(as.data.frame(x)) @@ -14,7 +16,8 @@ format.easycorrelation <- function(x, attri <- attributes(x) - out <- insight::format_table(x, + out <- insight::format_table( + x, digits = .retrieve_arg_from_attr(attri, digits, default = 2), stars = .retrieve_arg_from_attr(attri, stars, default = TRUE), p_digits = .retrieve_arg_from_attr(attri, p_digits, default = "apa"), @@ -24,25 +27,32 @@ format.easycorrelation <- function(x, out$Method <- NULL out$n_Obs <- NULL - attr(out, "table_footer") <- .format_easycorrelation_footer(x, format = format) - attr(out, "table_caption") <- .format_easycorrelation_caption(x, format = format) + attr(out, "table_footer") <- .format_easycorrelation_footer( + x, + format = format + ) + attr(out, "table_caption") <- .format_easycorrelation_caption( + x, + format = format + ) out } # Correlation matrix ----------------------------------------------------------- - #' @export -format.easycormatrix <- function(x, - digits = NULL, - p_digits = NULL, - stars = NULL, - include_significance = NULL, - format = NULL, - zap_small = NULL, - bf_exact = TRUE, - ...) { +format.easycormatrix <- function( + x, + digits = NULL, + p_digits = NULL, + stars = NULL, + include_significance = NULL, + format = NULL, + zap_small = NULL, + bf_exact = TRUE, + ... +) { # If it's a real matrix if (!"Parameter" %in% colnames(x)) { m <- as.data.frame(x) @@ -55,27 +65,30 @@ format.easycormatrix <- function(x, # Retrieve arguments from attributes (or assign default) digits <- .retrieve_arg_from_attr(attri, digits, default = 2) stars <- .retrieve_arg_from_attr(attri, stars, default = TRUE) - include_significance <- .retrieve_arg_from_attr(attri, include_significance, default = FALSE) + include_significance <- .retrieve_arg_from_attr( + attri, + include_significance, + default = FALSE + ) p_digits <- .retrieve_arg_from_attr(attri, p_digits, default = "apa") zap_small <- .retrieve_arg_from_attr(attri, zap_small, default = TRUE) - # Round and format values nums <- sapply(as.data.frame(x), is.numeric) x[, nums] <- sapply( as.data.frame(x)[, nums], insight::format_value, - digits = digits, zap_small = zap_small, ... + digits = digits, + zap_small = zap_small, + ... ) - # Deduct if stars only stars_only <- FALSE if (!include_significance && stars) { stars_only <- TRUE } - # Significance type <- names(attri)[names(attri) %in% c("BF", "pd", "p")][1] sig <- attri[[type]] @@ -111,11 +124,16 @@ format.easycormatrix <- function(x, } if (!stars_only) { - sig[, nums] <- sapply(sig[, nums], function(x) ifelse(x != "", paste0(" (", x, ")"), "")) # nolint + sig[, nums] <- sapply(sig[, nums], function(x) { + ifelse(x != "", paste0(" (", x, ")"), "") + }) # nolint } if (include_significance || stars) { - x[, nums] <- paste0(as.matrix(as.data.frame(x)[, nums]), as.matrix(sig[, nums])) + x[, nums] <- paste0( + as.matrix(as.data.frame(x)[, nums]), + as.matrix(sig[, nums]) + ) } } @@ -129,8 +147,14 @@ format.easycormatrix <- function(x, } } - attr(out, "table_footer") <- .format_easycorrelation_footer(x, format = format) - attr(out, "table_caption") <- .format_easycorrelation_caption(x, format = format) + attr(out, "table_footer") <- .format_easycorrelation_footer( + x, + format = format + ) + attr(out, "table_caption") <- .format_easycorrelation_caption( + x, + format = format + ) out } @@ -169,7 +193,8 @@ format.easycormatrix <- function(x, # remove empty elements footer <- footer[nzchar(footer, keepNA = TRUE)] # create list or separate by ";" - footer <- switch(format, + footer <- switch( + format, html = paste(footer, collapse = "; "), as.list(footer) ) @@ -190,7 +215,10 @@ format.easycormatrix <- function(x, prefix <- "Correlation Matrix (" } if (is.null(format) || format == "text") { - caption <- c(paste0("# ", prefix, unique(attributes(x)$method), "-method)"), "blue") + caption <- c( + paste0("# ", prefix, unique(attributes(x)$method), "-method)"), + "blue" + ) } else { caption <- paste0(prefix, unique(attributes(x)$method), "-method)") } @@ -201,7 +229,6 @@ format.easycormatrix <- function(x, # Arguments retrieving ---------------------------------------------------- - #' @keywords internal .retrieve_arg_from_attr <- function(attri, arg, default) { arg_name <- deparse(substitute(arg)) @@ -209,7 +236,11 @@ format.easycormatrix <- function(x, if (is.null(arg)) { if (arg_name %in% names(attri)) { arg <- attri[[arg_name]] - } else if ("additional_arguments" %in% names(attri) && arg_name %in% names(attri$additional_arguments)) { + } else if ( + "additional_arguments" %in% + names(attri) && + arg_name %in% names(attri$additional_arguments) + ) { arg <- attri$additional_arguments[[arg_name]] } else { arg <- default # That's the real default diff --git a/R/methods_print.R b/R/methods_print.R index 1a9bd54d..91e6a67d 100644 --- a/R/methods_print.R +++ b/R/methods_print.R @@ -1,6 +1,5 @@ # Console ----------------------------------------------------------------- - #' @export print.easycorrelation <- function(x, ...) { cat(insight::export_table(format(x, ...), ...)) @@ -39,7 +38,16 @@ print.easymatrixlist <- function(x, cols = "auto", ...) { #' @export print.grouped_easymatrixlist <- function(x, cols = "auto", ...) { for (i in names(x)) { - cat(rep("=", nchar(i) + 2), "\n ", i, " ", "\n", rep("=", nchar(i) + 2), "\n\n", sep = "") + cat( + rep("=", nchar(i) + 2), + "\n ", + i, + " ", + "\n", + rep("=", nchar(i) + 2), + "\n\n", + sep = "" + ) print(x[[i]], ...) cat("\n") } @@ -47,12 +55,14 @@ print.grouped_easymatrixlist <- function(x, cols = "auto", ...) { # MD and HTML -------------------------------------------------------------- -.print_md_html_easycorrelation <- function(x, - digits = NULL, - p_digits = NULL, - stars = NULL, - format = "markdown", - ...) { +.print_md_html_easycorrelation <- function( + x, + digits = NULL, + p_digits = NULL, + stars = NULL, + format = "markdown", + ... +) { formatted_table <- format( x, digits = digits, @@ -75,11 +85,13 @@ print.grouped_easymatrixlist <- function(x, cols = "auto", ...) { #' @rdname display.easycormatrix #' @export -print_md.easycorrelation <- function(x, - digits = NULL, - p_digits = NULL, - stars = NULL, - ...) { +print_md.easycorrelation <- function( + x, + digits = NULL, + p_digits = NULL, + stars = NULL, + ... +) { .print_md_html_easycorrelation( x, digits = digits, @@ -93,11 +105,13 @@ print_md.easycorrelation <- function(x, #' @rdname display.easycormatrix #' @export -print_html.easycorrelation <- function(x, - digits = NULL, - p_digits = NULL, - stars = NULL, - ...) { +print_html.easycorrelation <- function( + x, + digits = NULL, + p_digits = NULL, + stars = NULL, + ... +) { .print_md_html_easycorrelation( x, digits = digits, @@ -109,13 +123,15 @@ print_html.easycorrelation <- function(x, } -.print_md_html_easycormatrix <- function(x, - digits = NULL, - p_digits = NULL, - stars = NULL, - include_significance = NULL, - format = "markdown", - ...) { +.print_md_html_easycormatrix <- function( + x, + digits = NULL, + p_digits = NULL, + stars = NULL, + include_significance = NULL, + format = "markdown", + ... +) { formatted_table <- format( x, digits = digits, @@ -139,12 +155,14 @@ print_html.easycorrelation <- function(x, #' @rdname display.easycormatrix #' @export -print_md.easycormatrix <- function(x, - digits = NULL, - p_digits = NULL, - stars = NULL, - include_significance = NULL, - ...) { +print_md.easycormatrix <- function( + x, + digits = NULL, + p_digits = NULL, + stars = NULL, + include_significance = NULL, + ... +) { .print_md_html_easycormatrix( x, digits = digits, @@ -159,12 +177,14 @@ print_md.easycormatrix <- function(x, #' @rdname display.easycormatrix #' @export -print_html.easycormatrix <- function(x, - digits = NULL, - p_digits = NULL, - stars = NULL, - include_significance = NULL, - ...) { +print_html.easycormatrix <- function( + x, + digits = NULL, + p_digits = NULL, + stars = NULL, + include_significance = NULL, + ... +) { .print_md_html_easycormatrix( x, digits = digits, diff --git a/R/utils_create_diagonal.R b/R/utils_create_diagonal.R index 11d6350a..83ef48bf 100644 --- a/R/utils_create_diagonal.R +++ b/R/utils_create_diagonal.R @@ -5,39 +5,95 @@ "Parameter2" = unique(params$Parameter1) ) - if ("Group" %in% names(params)) diagonal$Group <- unique(params$Group)[1] - if ("r" %in% names(params)) diagonal$r <- 1 - if ("rho" %in% names(params)) diagonal$rho <- 1 - if ("tau" %in% names(params)) diagonal$tau <- 1 - if ("p" %in% names(params)) diagonal$p <- 0 - if ("t" %in% names(params)) diagonal$t <- Inf - if ("S" %in% names(params)) diagonal$S <- Inf - if ("z" %in% names(params)) diagonal$z <- Inf - if ("df" %in% names(params)) diagonal$df <- unique(params$df)[1] - if ("df_error" %in% names(params)) diagonal$df_error <- unique(params$df_error)[1] - if ("CI" %in% names(params)) diagonal$CI <- unique(params$CI)[1] - if ("CI_low" %in% names(params)) diagonal$CI_low <- 1 - if ("CI_high" %in% names(params)) diagonal$CI_high <- 1 - if ("Method" %in% names(params)) diagonal$Method <- unique(params$Method)[1] - if ("n_Obs" %in% names(params)) diagonal$n_Obs <- unique(params$n_Obs)[1] + if ("Group" %in% names(params)) { + diagonal$Group <- unique(params$Group)[1] + } + if ("r" %in% names(params)) { + diagonal$r <- 1 + } + if ("rho" %in% names(params)) { + diagonal$rho <- 1 + } + if ("tau" %in% names(params)) { + diagonal$tau <- 1 + } + if ("p" %in% names(params)) { + diagonal$p <- 0 + } + if ("t" %in% names(params)) { + diagonal$t <- Inf + } + if ("S" %in% names(params)) { + diagonal$S <- Inf + } + if ("z" %in% names(params)) { + diagonal$z <- Inf + } + if ("df" %in% names(params)) { + diagonal$df <- unique(params$df)[1] + } + if ("df_error" %in% names(params)) { + diagonal$df_error <- unique(params$df_error)[1] + } + if ("CI" %in% names(params)) { + diagonal$CI <- unique(params$CI)[1] + } + if ("CI_low" %in% names(params)) { + diagonal$CI_low <- 1 + } + if ("CI_high" %in% names(params)) { + diagonal$CI_high <- 1 + } + if ("Method" %in% names(params)) { + diagonal$Method <- unique(params$Method)[1] + } + if ("n_Obs" %in% names(params)) { + diagonal$n_Obs <- unique(params$n_Obs)[1] + } # Bayesian - if ("Median" %in% names(params)) diagonal$Median <- 1 - if ("Mean" %in% names(params)) diagonal$Mean <- 1 - if ("MAP" %in% names(params)) diagonal$MAP <- 1 - if ("SD" %in% names(params)) diagonal$SD <- 0 - if ("MAD" %in% names(params)) diagonal$MAD <- 0 - if ("pd" %in% names(params)) diagonal$pd <- 1 - if ("ROPE_Percentage" %in% names(params)) diagonal$ROPE_Percentage <- 0 - if ("BF" %in% names(params)) diagonal$BF <- Inf - if ("log_BF" %in% names(params)) diagonal$log_BF <- Inf - if ("Prior_Distribution" %in% names(params)) diagonal$Prior_Distribution <- unique(params$Prior_Distribution)[1] - if ("Prior_Location" %in% names(params)) diagonal$Prior_Location <- unique(params$Prior_Location)[1] - if ("Prior_Scale" %in% names(params)) diagonal$Prior_Scale <- unique(params$Prior_Scale)[1] + if ("Median" %in% names(params)) { + diagonal$Median <- 1 + } + if ("Mean" %in% names(params)) { + diagonal$Mean <- 1 + } + if ("MAP" %in% names(params)) { + diagonal$MAP <- 1 + } + if ("SD" %in% names(params)) { + diagonal$SD <- 0 + } + if ("MAD" %in% names(params)) { + diagonal$MAD <- 0 + } + if ("pd" %in% names(params)) { + diagonal$pd <- 1 + } + if ("ROPE_Percentage" %in% names(params)) { + diagonal$ROPE_Percentage <- 0 + } + if ("BF" %in% names(params)) { + diagonal$BF <- Inf + } + if ("log_BF" %in% names(params)) { + diagonal$log_BF <- Inf + } + if ("Prior_Distribution" %in% names(params)) { + diagonal$Prior_Distribution <- unique(params$Prior_Distribution)[1] + } + if ("Prior_Location" %in% names(params)) { + diagonal$Prior_Location <- unique(params$Prior_Location)[1] + } + if ("Prior_Scale" %in% names(params)) { + diagonal$Prior_Scale <- unique(params$Prior_Scale)[1] + } for (var in names(params)[!names(params) %in% names(diagonal)]) { if (length(unique(params[[var]])) > 1L) { - insight::format_error("Something's unexpected happened when creating the diagonal data. Please open an issue at https://github.com/easystats/correlation/issues") + insight::format_error( + "Something's unexpected happened when creating the diagonal data. Please open an issue at https://github.com/easystats/correlation/issues" + ) } diagonal[[var]] <- unique(params[[var]])[1] } diff --git a/R/utils_get_combinations.R b/R/utils_get_combinations.R index 4c9612be..60849f6a 100644 --- a/R/utils_get_combinations.R +++ b/R/utils_get_combinations.R @@ -1,11 +1,17 @@ #' @keywords internal -.get_combinations <- function(data, - data2 = NULL, - redundant = TRUE, - include_factors = TRUE, - multilevel = FALSE, - method = "pearson") { - data <- .clean_data(data, include_factors = include_factors, multilevel = multilevel) +.get_combinations <- function( + data, + data2 = NULL, + redundant = TRUE, + include_factors = TRUE, + multilevel = FALSE, + method = "pearson" +) { + data <- .clean_data( + data, + include_factors = include_factors, + multilevel = multilevel + ) if (method == "polychoric") { vars <- names(data) @@ -15,18 +21,23 @@ vars <- names(data) } - # Find pairs if (is.null(data2)) { vars2 <- vars } else { - data2 <- .clean_data(data2, include_factors = include_factors, multilevel = multilevel) + data2 <- .clean_data( + data2, + include_factors = include_factors, + multilevel = multilevel + ) data2_nums <- data2[sapply(data2, is.numeric)] vars2 <- names(data2_nums) } combinations <- expand.grid(vars, vars2, stringsAsFactors = FALSE) - combinations <- combinations[order(match(combinations$Var1, vars), match(combinations$Var2, vars2)), ] + combinations <- combinations[ + order(match(combinations$Var1, vars), match(combinations$Var2, vars2)), + ] row.names(combinations) <- NULL names(combinations) <- c("Parameter1", "Parameter2") diff --git a/R/utils_get_matrix.R b/R/utils_get_matrix.R index fcc6d610..472a4fc1 100644 --- a/R/utils_get_matrix.R +++ b/R/utils_get_matrix.R @@ -1,6 +1,10 @@ #' @keywords internal .get_matrix <- function(data, square = FALSE) { - if ((all(data$Parameter1 %in% data$Parameter2) && all(data$Parameter2 %in% data$Parameter1)) || square) { + if ( + (all(data$Parameter1 %in% data$Parameter2) && + all(data$Parameter2 %in% data$Parameter1)) || + square + ) { vars <- as.character(unique(c(data$Parameter1, data$Parameter2))) dim <- length(vars) m <- matrix(nrow = dim, ncol = dim, dimnames = list(vars, vars)) diff --git a/R/utils_remove_redundant.R b/R/utils_remove_redundant.R index abb07266..89008ba7 100644 --- a/R/utils_remove_redundant.R +++ b/R/utils_remove_redundant.R @@ -1,10 +1,15 @@ #' @keywords internal .remove_redundant <- function(params) { - if (all(params$Parameter1 %in% params$Parameter2) && all(params$Parameter2 %in% params$Parameter1)) { + if ( + all(params$Parameter1 %in% params$Parameter2) && + all(params$Parameter2 %in% params$Parameter1) + ) { m <- .get_matrix(params) m[upper.tri(m, diag = TRUE)] <- NA rows_NA <- .get_rows_non_NA(m) - out <- params[!paste0(params$Parameter1, "_", params$Parameter2) %in% rows_NA, ] + out <- params[ + !paste0(params$Parameter1, "_", params$Parameter2) %in% rows_NA, + ] } else { # Might be some edgecases here out <- params @@ -23,7 +28,10 @@ # inverse parameters inversed <- params - inversed[, c("Parameter1", "Parameter2")] <- params[, c("Parameter2", "Parameter1")] + inversed[, c("Parameter1", "Parameter2")] <- params[, c( + "Parameter2", + "Parameter1" + )] # bind and get diagonal data params <- rbind(params, inversed) @@ -38,7 +46,12 @@ # Reorder if (!is.null(data)) { - params <- params[order(match(params$Parameter1, names(data)), match(params$Parameter2, names(data))), ] + params <- params[ + order( + match(params$Parameter1, names(data)), + match(params$Parameter2, names(data)) + ), + ] } params diff --git a/R/visualisation_recipe.cor_test.R b/R/visualisation_recipe.cor_test.R index 7dc69c4d..0396c14b 100644 --- a/R/visualisation_recipe.cor_test.R +++ b/R/visualisation_recipe.cor_test.R @@ -16,25 +16,31 @@ #' ) #' } #' @export -visualisation_recipe.easycor_test <- function(x, - show_data = "point", - show_text = "subtitle", - smooth = NULL, - point = NULL, - text = NULL, - labs = NULL, - ...) { +visualisation_recipe.easycor_test <- function( + x, + show_data = "point", + show_text = "subtitle", + smooth = NULL, + point = NULL, + text = NULL, + labs = NULL, + ... +) { data <- attributes(x)$data # Text subtitle <- NULL title <- NULL - if (!is.null(show_text) && show_text == "subtitle") subtitle <- cor_text(x, ...) - if (!is.null(show_text) && show_text == "title") title <- cor_text(x, ...) - + if (!is.null(show_text) && show_text == "subtitle") { + subtitle <- cor_text(x, ...) + } + if (!is.null(show_text) && show_text == "title") { + title <- cor_text(x, ...) + } # Get scatter plot - layers <- .see_scatter(data, + layers <- .see_scatter( + data, cor_results = x, x = x$Parameter1, y = x$Parameter2, @@ -50,11 +56,16 @@ visualisation_recipe.easycor_test <- function(x, ) # Text - if (!is.null(show_text) && isTRUE(show_text) && show_text %in% c("text", "label")) { + if ( + !is.null(show_text) && + isTRUE(show_text) && + show_text %in% c("text", "label") + ) { # Add text x$label <- cor_text(x, ...) x$label_x <- max(data[[x$Parameter1]], na.rm = TRUE) - x$label_y <- max(data[[x$Parameter2]], na.rm = TRUE) + 0.05 * diff(range(data[[x$Parameter2]], na.rm = TRUE)) + x$label_y <- max(data[[x$Parameter2]], na.rm = TRUE) + + 0.05 * diff(range(data[[x$Parameter2]], na.rm = TRUE)) l <- paste0("l", length(layers) + 1) layers[[l]] <- list( @@ -71,7 +82,11 @@ visualisation_recipe.easycor_test <- function(x, } # Out - class(layers) <- c("visualisation_recipe", "see_visualisation_recipe", class(layers)) + class(layers) <- c( + "visualisation_recipe", + "see_visualisation_recipe", + class(layers) + ) attr(layers, "data") <- data layers } @@ -79,21 +94,22 @@ visualisation_recipe.easycor_test <- function(x, # see_scatter ------------------------------------------------------------- - -.see_scatter <- function(data, - cor_results, - x, - y, - show_data = "point", - show_text = "text", - smooth = NULL, - point = NULL, - text = NULL, - labs = NULL, - title = NULL, - subtitle = NULL, - type = show_data, - ...) { +.see_scatter <- function( + data, + cor_results, + x, + y, + show_data = "point", + show_text = "text", + smooth = NULL, + point = NULL, + text = NULL, + labs = NULL, + title = NULL, + subtitle = NULL, + type = show_data, + ... +) { # Keep only relevant variables (lighter) and complete cases data <- data[stats::complete.cases(data[c(x, y)]), ] @@ -119,7 +135,10 @@ visualisation_recipe.easycor_test <- function(x, ) ) if (!is.null(smooth)) { - layers[[paste0("l", l)]] <- utils::modifyList(layers[[paste0("l", l)]], smooth) + layers[[paste0("l", l)]] <- utils::modifyList( + layers[[paste0("l", l)]], + smooth + ) } l <- l + 1 @@ -133,7 +152,10 @@ visualisation_recipe.easycor_test <- function(x, ) ) if (!is.null(point)) { - layers[[paste0("l", l)]] <- utils::modifyList(layers[[paste0("l", l)]], point) + layers[[paste0("l", l)]] <- utils::modifyList( + layers[[paste0("l", l)]], + point + ) } l <- l + 1 @@ -157,9 +179,16 @@ visualisation_recipe.easycor_test <- function(x, # l <- l + 1 # Labs - layers[[paste0("l", l)]] <- list(geom = "labs", subtitle = subtitle, title = title) + layers[[paste0("l", l)]] <- list( + geom = "labs", + subtitle = subtitle, + title = title + ) if (!is.null(labs)) { - layers[[paste0("l", l)]] <- utils::modifyList(layers[[paste0("l", l)]], labs) + layers[[paste0("l", l)]] <- utils::modifyList( + layers[[paste0("l", l)]], + labs + ) } layers diff --git a/R/visualisation_recipe.easycormatrix.R b/R/visualisation_recipe.easycormatrix.R index 6a24a3ec..a36768b0 100644 --- a/R/visualisation_recipe.easycormatrix.R +++ b/R/visualisation_recipe.easycormatrix.R @@ -45,18 +45,20 @@ #' plot(layers) + theme_modern() #' } #' @export -visualisation_recipe.easycormatrix <- function(x, - show_data = "tile", - show_text = "text", - show_legend = TRUE, - tile = NULL, - point = NULL, - text = NULL, - scale = NULL, - scale_fill = NULL, - labs = NULL, - type = show_data, - ...) { +visualisation_recipe.easycormatrix <- function( + x, + show_data = "tile", + show_text = "text", + show_legend = TRUE, + tile = NULL, + point = NULL, + text = NULL, + scale = NULL, + scale_fill = NULL, + labs = NULL, + type = show_data, + ... +) { # handle alias if (!missing(type)) { show_data <- type @@ -95,7 +97,8 @@ visualisation_recipe.easycormatrix <- function(x, colnames <- names(x)[names(x) != "Parameter1"] # Reshape to long - data <- datawizard::reshape_longer(x, + data <- datawizard::reshape_longer( + x, select = colnames, names_to = "Parameter2", values_to = "r" @@ -105,7 +108,8 @@ visualisation_recipe.easycormatrix <- function(x, if (is.null(data_text)) { data$Text <- paste0(insight::format_value(data$r, zap_small = TRUE)) } else { - temp <- datawizard::reshape_longer(data_text, + temp <- datawizard::reshape_longer( + data_text, select = colnames, names_to = "Parameter2", values_to = "Text" @@ -146,7 +150,8 @@ visualisation_recipe.easycormatrix <- function(x, if (isTRUE(show_data) || show_data %in% c("tile", "tiles")) { layers[[paste0("l", l)]] <- .visualisation_easycormatrix_data( type = "tile", - data, x = "Parameter2", + data, + x = "Parameter2", y = "Parameter1", fill = "r", args = tile, @@ -167,7 +172,6 @@ visualisation_recipe.easycormatrix <- function(x, l <- l + 1 } - # Add text if (!is.null(show_text) && !isFALSE(show_text)) { layers[[paste0("l", l)]] <- .visualisation_easycormatrix_text( @@ -201,12 +205,21 @@ visualisation_recipe.easycormatrix <- function(x, # Origin at 0 if (!is.null(show_data) && show_data %in% c("tile", "tiles")) { - layers[[paste0("l", l)]] <- .visualisation_easycormatrix_scale(which = "x_discrete", scale = scale) + layers[[paste0("l", l)]] <- .visualisation_easycormatrix_scale( + which = "x_discrete", + scale = scale + ) l <- l + 1 - layers[[paste0("l", l)]] <- .visualisation_easycormatrix_scale(which = "y_discrete", scale = scale) + layers[[paste0("l", l)]] <- .visualisation_easycormatrix_scale( + which = "y_discrete", + scale = scale + ) l <- l + 1 } else if (show_data %in% c("point", "points")) { - layers[[paste0("l", l)]] <- .visualisation_easycormatrix_scale(which = "size", scale = scale) + layers[[paste0("l", l)]] <- .visualisation_easycormatrix_scale( + which = "size", + scale = scale + ) l <- l + 1 } @@ -214,7 +227,11 @@ visualisation_recipe.easycormatrix <- function(x, layers[[paste0("l", l)]] <- .visualisation_easycormatrix_labs(labs) # Out - class(layers) <- c("visualisation_recipe", "see_visualisation_recipe", class(layers)) + class(layers) <- c( + "visualisation_recipe", + "see_visualisation_recipe", + class(layers) + ) attr(layers, "data") <- data layers } @@ -222,14 +239,16 @@ visualisation_recipe.easycormatrix <- function(x, # Layer - Data ------------------------------------------------------------- -.visualisation_easycormatrix_data <- function(type = "tile", - data, - x, - y, - fill, - args = NULL, - dot_args = NULL, - abs_fill = NULL) { +.visualisation_easycormatrix_data <- function( + type = "tile", + data, + x, + y, + fill, + args = NULL, + dot_args = NULL, + abs_fill = NULL +) { out <- list( geom = type, data = data, @@ -258,14 +277,21 @@ visualisation_recipe.easycormatrix <- function(x, } else { out$aes$fill <- fill } - if (!is.null(args)) out <- utils::modifyList(out, args) # Update with additional args + if (!is.null(args)) { + out <- utils::modifyList(out, args) + } # Update with additional args out } # Layer - Scale Fill ------------------------------------------------------------- -.visualisation_easycormatrix_scale_fill <- function(type = "fill", data, scale_fill = NULL, show_legend = TRUE) { +.visualisation_easycormatrix_scale_fill <- function( + type = "fill", + data, + scale_fill = NULL, + show_legend = TRUE +) { low_lim <- ifelse(min(data$r, na.rm = TRUE) < 0, -1, 0) high_lim <- ifelse(max(data$r, na.rm = TRUE) > 0, 1, 0) @@ -281,14 +307,23 @@ visualisation_recipe.easycormatrix <- function(x, name = "Correlation", guide = ifelse(isFALSE(show_legend), "none", "legend") ) - if (!is.null(scale_fill)) out <- utils::modifyList(out, scale_fill) # Update with additional args + if (!is.null(scale_fill)) { + out <- utils::modifyList(out, scale_fill) + } # Update with additional args out } # Layer - Text ------------------------------------------------------------- -.visualisation_easycormatrix_text <- function(data, x, y, label, show_text = "text", text = NULL) { +.visualisation_easycormatrix_text <- function( + data, + x, + y, + label, + show_text = "text", + text = NULL +) { out <- list( geom = show_text, data = data, @@ -298,15 +333,19 @@ visualisation_recipe.easycormatrix <- function(x, label = label ) ) - if (!is.null(text)) out <- utils::modifyList(out, text) # Update with additional args + if (!is.null(text)) { + out <- utils::modifyList(out, text) + } # Update with additional args out } # Layer - Scale ------------------------------------------------------------------- - -.visualisation_easycormatrix_scale <- function(which = "x_discrete", scale = NULL) { +.visualisation_easycormatrix_scale <- function( + which = "x_discrete", + scale = NULL +) { if (which == "size") { out <- list( geom = "scale_size", @@ -319,14 +358,15 @@ visualisation_recipe.easycormatrix <- function(x, ) } - if (!is.null(scale)) out <- utils::modifyList(out, scale) # Update with additional args + if (!is.null(scale)) { + out <- utils::modifyList(out, scale) + } # Update with additional args out } # Layer - Labs ------------------------------------------------------------------- - .visualisation_easycormatrix_labs <- function(labs = NULL) { out <- list( geom = "labs", @@ -334,6 +374,8 @@ visualisation_recipe.easycormatrix <- function(x, y = NULL, title = "Correlation Matrix" ) - if (!is.null(labs)) out <- utils::modifyList(out, labs) # Update with additional args + if (!is.null(labs)) { + out <- utils::modifyList(out, labs) + } # Update with additional args out } diff --git a/R/visualisation_recipe.easycorrelation.R b/R/visualisation_recipe.easycorrelation.R index d80dc779..2646fd0f 100644 --- a/R/visualisation_recipe.easycorrelation.R +++ b/R/visualisation_recipe.easycorrelation.R @@ -26,13 +26,18 @@ visualisation_recipe.easycorrelation <- function(x, ...) { layers[["l2"]] <- list(geom = "ggraph::geom_node_point", size = 22) layers[["l3"]] <- list( geom = "ggraph::geom_node_text", - aes = list(label = "name"), colour = "white" + aes = list(label = "name"), + colour = "white" ) layers[["l4"]] <- list(geom = "ggraph::theme_graph", base_family = "sans") layers[["l5"]] <- list(geom = "guides", edge_width = "none") # Out - class(layers) <- c("visualisation_recipe", "see_visualisation_recipe", class(layers)) + class(layers) <- c( + "visualisation_recipe", + "see_visualisation_recipe", + class(layers) + ) attr(layers, "data") <- data attr(layers, "layout") <- "kk" attr(layers, "ggraph") <- TRUE diff --git a/WIP/spcor_to_cor.R b/WIP/spcor_to_cor.R index 90a7dd45..2745bbe2 100644 --- a/WIP/spcor_to_cor.R +++ b/WIP/spcor_to_cor.R @@ -1,6 +1,11 @@ #' @rdname cor_to_pcor #' @export -spcor_to_cor <- function(spcor = NULL, cov = NULL, semi = FALSE, tol = .Machine$double.eps^(2 / 3)) { +spcor_to_cor <- function( + spcor = NULL, + cov = NULL, + semi = FALSE, + tol = .Machine$double.eps^(2 / 3) +) { # Get cor spcor <- .get_cor(spcor, cov) @@ -8,7 +13,9 @@ spcor_to_cor <- function(spcor = NULL, cov = NULL, semi = FALSE, tol = .Machine$ m <- -spcor diag(m) <- -diag(m) - stop("Cannot convert semi-partial correlations to correlations yet. We need help for that.") + stop( + "Cannot convert semi-partial correlations to correlations yet. We need help for that." + ) # if(is.null(cov)){ # stop("Covariance matrix (or vector of SD of variables) needs to be passed for semi-partial correlations.") # } else{ diff --git a/WIP/utils_bootstrapping.R b/WIP/utils_bootstrapping.R index 592bc824..6d55f583 100644 --- a/WIP/utils_bootstrapping.R +++ b/WIP/utils_bootstrapping.R @@ -4,15 +4,15 @@ strap <- replicate(n, .resample(data), simplify = FALSE) # add resample ID, may be used for other functions - for (i in seq_len(length(strap))) strap[[i]]$Resample_id <- i + for (i in seq_len(length(strap))) { + strap[[i]]$Resample_id <- i + } # return as list variable data.frame(bootstraps = I(strap)) } - - #' @keywords internal .resample <- function(data) { structure( @@ -25,11 +25,14 @@ } - - #' @importFrom stats qt sd quantile na.omit #' @keywords internal -.bootstrapped_ci <- function(data, select = NULL, method = c("normal", "quantile"), ci.lvl = .95) { +.bootstrapped_ci <- function( + data, + select = NULL, + method = c("normal", "quantile"), + ci.lvl = .95 +) { # match arguments method <- match.arg(method) @@ -45,7 +48,11 @@ # bootstrap values or quantiles if (method == "normal") { # get bootstrap standard error - bootse <- stats::qt((1 + ci.lvl) / 2, df = length(stats::na.omit(x)) - 1) * stats::sd(x, na.rm = T) + bootse <- stats::qt( + (1 + ci.lvl) / 2, + df = length(stats::na.omit(x)) - 1 + ) * + stats::sd(x, na.rm = T) # lower and upper confidence interval ci <- mean(x, na.rm = T) + c(-bootse, bootse) } else { @@ -59,16 +66,12 @@ } - - #' @keywords internal .transform_boot_result <- function(result) { as.data.frame(t(as.data.frame(result))) } - - #' @keywords internal as.data.frame.correlation_resample <- function(x, ...) { x$data[x$id, , drop = FALSE] diff --git a/WIP/utils_reorder_matrix.R b/WIP/utils_reorder_matrix.R index 9b3b92ff..543306d7 100644 --- a/WIP/utils_reorder_matrix.R +++ b/WIP/utils_reorder_matrix.R @@ -14,7 +14,11 @@ stop("Matrix must be squared to be re-arranged.") } - reorder_distance <- stats::as.dist((1 - reorder_distance) / 2, diag = TRUE, upper = TRUE) + reorder_distance <- stats::as.dist( + (1 - reorder_distance) / 2, + diag = TRUE, + upper = TRUE + ) hc <- stats::hclust(reorder_distance, method = method) x <- x[hc$order, hc$order] x diff --git a/air.toml b/air.toml new file mode 100644 index 00000000..8e08bdbb --- /dev/null +++ b/air.toml @@ -0,0 +1,7 @@ +[format] +line-width = 80 +indent-width = 2 +indent-style = "space" +line-ending = "lf" +persistent-line-breaks = true +skip = ["tribble"] \ No newline at end of file diff --git a/paper/make_figures.R b/paper/make_figures.R index b3cdbf61..8a57b6ab 100644 --- a/paper/make_figures.R +++ b/paper/make_figures.R @@ -3,7 +3,6 @@ library(correlation) library(see) - # Figure 1 ---------------------------------------------------------------- # Generate data @@ -15,7 +14,11 @@ data <- arrange(data, V2) # Outliers data$V2[c(150, 185)] <- c(max(data$V2) * 1, max(data$V2) * 1) -data$V2[c(1, 5, 10)] <- c(min(data$V2) * 2, max(data$V2) * 1, min(data$V2) * 1.5) +data$V2[c(1, 5, 10)] <- c( + min(data$V2) * 2, + max(data$V2) * 1, + min(data$V2) * 1.5 +) # Rescale to match coef data$V2 <- datawizard::data_rescale(data$V2, to = c(0, 1)) @@ -23,14 +26,64 @@ data$V2 <- datawizard::data_rescale(data$V2, to = c(0, 1)) # Correlation results rez <- rbind( - select(cor_test(data, "V1", "V2", method = "Pearson"), r, CI_low, CI_high, Method), - select(cor_test(data, "V1", "V2", method = "Spearman"), r = rho, CI_low, CI_high, Method), - select(cor_test(data, "V1", "V2", method = "Kendall"), r = tau, CI_low, CI_high, Method), - select(cor_test(data, "V1", "V2", method = "biweight"), r, CI_low, CI_high, Method), - select(cor_test(data, "V1", "V2", method = "percentage"), r, CI_low, CI_high, Method), - select(cor_test(data, "V1", "V2", method = "distance", corrected = FALSE), r, CI_low, CI_high, Method), - select(cor_test(data, "V1", "V2", method = "shepherd"), r = rho, CI_low, CI_high, Method), - mutate(select(cor_test(data, "V1", "V2", method = "Pearson", bayesian = TRUE), r = rho, CI_low, CI_high), Method = "Bayesian") + select( + cor_test(data, "V1", "V2", method = "Pearson"), + r, + CI_low, + CI_high, + Method + ), + select( + cor_test(data, "V1", "V2", method = "Spearman"), + r = rho, + CI_low, + CI_high, + Method + ), + select( + cor_test(data, "V1", "V2", method = "Kendall"), + r = tau, + CI_low, + CI_high, + Method + ), + select( + cor_test(data, "V1", "V2", method = "biweight"), + r, + CI_low, + CI_high, + Method + ), + select( + cor_test(data, "V1", "V2", method = "percentage"), + r, + CI_low, + CI_high, + Method + ), + select( + cor_test(data, "V1", "V2", method = "distance", corrected = FALSE), + r, + CI_low, + CI_high, + Method + ), + select( + cor_test(data, "V1", "V2", method = "shepherd"), + r = rho, + CI_low, + CI_high, + Method + ), + mutate( + select( + cor_test(data, "V1", "V2", method = "Pearson", bayesian = TRUE), + r = rho, + CI_low, + CI_high + ), + Method = "Bayesian" + ) ) # Format correlation to match data input from scatter @@ -39,7 +92,10 @@ rez <- rez %>% mutate( Method = forcats::fct_reorder(as.factor(Method), r), V2 = r, - x = stringr::str_remove_all(levels(ggplot2::cut_interval(data$V1, n = n())), "[\\(\\[\\]]") + x = stringr::str_remove_all( + levels(ggplot2::cut_interval(data$V1, n = n())), + "[\\(\\[\\]]" + ) ) %>% separate(x, into = c("low", "high"), sep = ",") %>% mutate(V1 = (as.numeric(high) + as.numeric(low)) / 2) @@ -48,7 +104,6 @@ rez <- rez %>% # rez[rez$Method=="Spearman", c("CI_low", "CI_high")] <- rep(rez[rez$Method=="Spearman", "r"], 2) # rez[rez$Method=="Kendall", c("CI_low", "CI_high")] <- rep(rez[rez$Method=="Kendall", "r"], 2) - # Initialize plot fig1 <- ggplot(data, aes(x = V1, y = V2)) + see::theme_modern() + @@ -60,7 +115,13 @@ fig1 <- ggplot(data, aes(x = V1, y = V2)) + scale_colour_material_d("rainbow") + # rez plot - geom_segment(data = rez, aes(xend = V1, yend = -Inf, colour = Method), size = 20, alpha = 0.6, key_glyph = "point") + + geom_segment( + data = rez, + aes(xend = V1, yend = -Inf, colour = Method), + size = 20, + alpha = 0.6, + key_glyph = "point" + ) + # geom_bar(data=rez, aes(fill=Method), stat = "identity") geom_errorbar( data = rez, @@ -81,14 +142,6 @@ fig1 ggsave("figure1.png", fig1, height = 6, width = see::golden_ratio(6), dpi = 300) - - - - - - - - # Figure 2 ---------------------------------------------------------------- fig2 <- correlation(iris) %>% diff --git a/tests/testthat/helper.R b/tests/testthat/helper.R index 0c5a12bd..afff3ed1 100644 --- a/tests/testthat/helper.R +++ b/tests/testthat/helper.R @@ -1,6 +1,11 @@ skip_if_not_or_load_if_installed <- function(package, minimum_version = NULL) { testthat::skip_if_not_installed(package, minimum_version = minimum_version) suppressMessages(suppressWarnings(suppressPackageStartupMessages( - require(package, warn.conflicts = FALSE, character.only = TRUE, quietly = TRUE) + require( + package, + warn.conflicts = FALSE, + character.only = TRUE, + quietly = TRUE + ) ))) } diff --git a/tests/testthat/test-cor_multilevel.R b/tests/testthat/test-cor_multilevel.R index 348acfc1..bae30d8a 100644 --- a/tests/testthat/test-cor_multilevel.R +++ b/tests/testthat/test-cor_multilevel.R @@ -2,10 +2,21 @@ test_that("comparison rmcorr", { skip_if_not_or_load_if_installed("lme4") skip_if_not_or_load_if_installed("rmcorr") set.seed(123) - rez_rmcorr <- rmcorr::rmcorr(Species, Sepal.Length, Sepal.Width, dataset = iris) + rez_rmcorr <- rmcorr::rmcorr( + Species, + Sepal.Length, + Sepal.Width, + dataset = iris + ) set.seed(123) - rez <- cor_test(iris[c(1, 2, 5)], "Sepal.Length", "Sepal.Width", partial = TRUE, multilevel = TRUE) + rez <- cor_test( + iris[c(1, 2, 5)], + "Sepal.Length", + "Sepal.Width", + partial = TRUE, + multilevel = TRUE + ) expect_equal(rez$r, rez_rmcorr$r, tolerance = 0.001) expect_equal(rez$p, rez_rmcorr$p, tolerance = 0.001) @@ -19,9 +30,15 @@ test_that("Reductio ad absurdum", { skip_if_not_or_load_if_installed("lme4") cormatrix <- matrix( c( - 1.0, 0.3, 0.6, - 0.3, 1.0, 0.0, - 0.6, 0.0, 1.0 + 1.0, + 0.3, + 0.6, + 0.3, + 1.0, + 0.0, + 0.6, + 0.0, + 1.0 ), nrow = 3 ) @@ -36,6 +53,15 @@ test_that("Reductio ad absurdum", { rez <- suppressMessages(correlation(data, multilevel = TRUE, verbose = FALSE)) expect_equal(max(as.matrix(rez) - cormatrix), 0, tolerance = 0.01) - rez <- suppressMessages(correlation(data, multilevel = TRUE, partial = TRUE, verbose = FALSE)) - expect_equal(max(as.matrix(pcor_to_cor(rez)) - cormatrix), 0, tolerance = 0.01) + rez <- suppressMessages(correlation( + data, + multilevel = TRUE, + partial = TRUE, + verbose = FALSE + )) + expect_equal( + max(as.matrix(pcor_to_cor(rez)) - cormatrix), + 0, + tolerance = 0.01 + ) }) diff --git a/tests/testthat/test-cor_sort.R b/tests/testthat/test-cor_sort.R index 61886466..50271a58 100644 --- a/tests/testthat/test-cor_sort.R +++ b/tests/testthat/test-cor_sort.R @@ -19,7 +19,10 @@ test_that("cor_sort", { r2sort <- cor_sort(r2) expect_false(all(rownames(r2sort) == names(mtcars)[1:5])) - expect_identical(colnames(r2sort), c("am", "gear", "qsec", "vs", "wt", "carb")) + expect_identical( + colnames(r2sort), + c("am", "gear", "qsec", "vs", "wt", "carb") + ) expect_identical(rownames(r2sort), c("drat", "disp", "hp", "cyl", "mpg")) # heatmap(r2sort, Rowv = NA, Colv = NA) # visualize @@ -30,7 +33,10 @@ test_that("cor_sort", { expect_false(all(rez1$Parameter1 == rez1sort$Parameter1)) # Non-square - rez2 <- correlation::correlation(mtcars[names(mtcars)[1:5]], mtcars[names(mtcars)[6:11]]) + rez2 <- correlation::correlation( + mtcars[names(mtcars)[1:5]], + mtcars[names(mtcars)[6:11]] + ) rez2sort <- cor_sort(rez2) expect_false(all(rez2$Parameter1 == rez2sort$Parameter1)) diff --git a/tests/testthat/test-cor_test.R b/tests/testthat/test-cor_test.R index 36e9f920..501c03d0 100644 --- a/tests/testthat/test-cor_test.R +++ b/tests/testthat/test-cor_test.R @@ -7,7 +7,11 @@ test_that("cor_test frequentist", { test_that("cor_test kendall", { out <- cor_test(iris, "Petal.Length", "Petal.Width", method = "kendall") - out2 <- stats::cor.test(iris$Petal.Length, iris$Petal.Width, method = "kendall") + out2 <- stats::cor.test( + iris$Petal.Length, + iris$Petal.Width, + method = "kendall" + ) expect_equal(out$tau, out2$estimate[[1]], tolerance = 0.001) expect_equal(out$p, out2$p.value[[1]], tolerance = 0.001) @@ -23,15 +27,32 @@ test_that("cor_test bayesian", { df_1 <- cor_test(iris, "Petal.Length", "Petal.Width", bayesian = TRUE) set.seed(123) - df_2 <- cor_test(iris, "Petal.Length", "Petal.Width", method = "auto", bayesian = TRUE) + df_2 <- cor_test( + iris, + "Petal.Length", + "Petal.Width", + method = "auto", + bayesian = TRUE + ) expect_equal(df_1, df_2, tolerance = 0.001) - out2 <- cor_test(iris, "Petal.Length", "Petal.Width", method = "spearman", bayesian = TRUE) + out2 <- cor_test( + iris, + "Petal.Length", + "Petal.Width", + method = "spearman", + bayesian = TRUE + ) expect_equal(out2$rho, 0.9323004, tolerance = 0.01) df <- iris df$Petal.Length2 <- df$Petal.Length - out3 <- suppressWarnings(cor_test(df, "Petal.Length", "Petal.Length2", bayesian = TRUE)) + out3 <- suppressWarnings(cor_test( + df, + "Petal.Length", + "Petal.Length2", + bayesian = TRUE + )) expect_equal(out3$rho, 1.000, tolerance = 0.01) if (getRversion() >= "3.6") { @@ -45,14 +66,62 @@ test_that("cor_test bayesian", { } # unsupported - expect_error(cor_test(mtcars, "wt", "mpg", method = "biserial", bayesian = TRUE)) - expect_error(cor_test(mtcars, "wt", "mpg", method = "polychoric", bayesian = TRUE)) - expect_error(cor_test(mtcars, "wt", "mpg", method = "tetrachoric", bayesian = TRUE)) - expect_error(cor_test(mtcars, "wt", "mpg", method = "biweight", bayesian = TRUE)) - expect_error(cor_test(mtcars, "wt", "mpg", method = "distance", bayesian = TRUE)) - expect_error(cor_test(mtcars, "wt", "mpg", method = "percentage", bayesian = TRUE)) - expect_error(cor_test(mtcars, "wt", "mpg", method = "blomqvist", bayesian = TRUE)) - expect_error(cor_test(mtcars, "wt", "mpg", method = "hoeffding", bayesian = TRUE)) + expect_error(cor_test( + mtcars, + "wt", + "mpg", + method = "biserial", + bayesian = TRUE + )) + expect_error(cor_test( + mtcars, + "wt", + "mpg", + method = "polychoric", + bayesian = TRUE + )) + expect_error(cor_test( + mtcars, + "wt", + "mpg", + method = "tetrachoric", + bayesian = TRUE + )) + expect_error(cor_test( + mtcars, + "wt", + "mpg", + method = "biweight", + bayesian = TRUE + )) + expect_error(cor_test( + mtcars, + "wt", + "mpg", + method = "distance", + bayesian = TRUE + )) + expect_error(cor_test( + mtcars, + "wt", + "mpg", + method = "percentage", + bayesian = TRUE + )) + expect_error(cor_test( + mtcars, + "wt", + "mpg", + method = "blomqvist", + bayesian = TRUE + )) + expect_error(cor_test( + mtcars, + "wt", + "mpg", + method = "hoeffding", + bayesian = TRUE + )) expect_error(cor_test(mtcars, "wt", "mpg", method = "gamma", bayesian = TRUE)) }) @@ -64,12 +133,22 @@ test_that("cor_test tetrachoric", { data$Petal.Width_binary <- as.numeric(data$Petal.Width > 1.2) # With Factors / Binary - out <- cor_test(data, "Sepal.Width_binary", "Petal.Width_binary", method = "tetrachoric") + out <- cor_test( + data, + "Sepal.Width_binary", + "Petal.Width_binary", + method = "tetrachoric" + ) expect_equal(out$rho, -0.526, tolerance = 0.01) data$Petal.Width_ordinal <- as.factor(round(data$Petal.Width)) data$Sepal.Length_ordinal <- as.factor(round(data$Sepal.Length)) - out <- cor_test(data, "Petal.Width_ordinal", "Sepal.Length_ordinal", method = "polychoric") + out <- cor_test( + data, + "Petal.Width_ordinal", + "Sepal.Length_ordinal", + method = "polychoric" + ) # Curently CRAN checks show two possible results for this: if (isTRUE(all.equal(out$rho, 0.7507764, tolerance = 0.1))) { @@ -78,16 +157,34 @@ test_that("cor_test tetrachoric", { expect_equal(out$rho, 0.528, tolerance = 0.01) } - out <- cor_test(data, "Sepal.Width", "Sepal.Length_ordinal", method = "polychoric") + out <- cor_test( + data, + "Sepal.Width", + "Sepal.Length_ordinal", + method = "polychoric" + ) expect_equal(out$rho, -0.144, tolerance = 0.01) # Biserial - out <- cor_test(data, "Sepal.Width", "Petal.Width_binary", method = "pointbiserial") + out <- cor_test( + data, + "Sepal.Width", + "Petal.Width_binary", + method = "pointbiserial" + ) expect_equal(out$rho, -0.3212561, tolerance = 0.01) - out <- cor_test(data, "Sepal.Width", "Petal.Width_binary", method = "biserial") + out <- cor_test( + data, + "Sepal.Width", + "Petal.Width_binary", + method = "biserial" + ) expect_equal(out$rho, -0.403, tolerance = 0.01) - out_psych <- psych::biserial(data[["Sepal.Width"]], data[["Petal.Width_binary"]])[1] + out_psych <- psych::biserial( + data[["Sepal.Width"]], + data[["Petal.Width_binary"]] + )[1] set.seed(123) n <- 100 @@ -109,8 +206,20 @@ test_that("cor_test tetrachoric", { test_that("cor_test robust", { - out1 <- cor_test(iris, "Petal.Length", "Petal.Width", method = "pearson", ranktransform = TRUE) - out2 <- cor_test(iris, "Petal.Length", "Petal.Width", method = "spearman", ranktransform = FALSE) + out1 <- cor_test( + iris, + "Petal.Length", + "Petal.Width", + method = "pearson", + ranktransform = TRUE + ) + out2 <- cor_test( + iris, + "Petal.Length", + "Petal.Width", + method = "spearman", + ranktransform = FALSE + ) expect_equal(out1$r, out2$rho, tolerance = 0.01) }) @@ -142,7 +251,13 @@ test_that("cor_test shepherd", { skip_if_not_or_load_if_installed("BayesFactor") set.seed(333) - out2 <- cor_test(iris, "Petal.Length", "Petal.Width", method = "shepherd", bayesian = TRUE) + out2 <- cor_test( + iris, + "Petal.Length", + "Petal.Width", + method = "shepherd", + bayesian = TRUE + ) expect_equal(out2$rho, 0.9429992, tolerance = 0.01) }) @@ -180,16 +295,25 @@ test_that("cor_test gaussian", { out <- cor_test(iris, "Petal.Length", "Petal.Width", method = "gaussian") expect_equal(out$r, 0.87137, tolerance = 0.01) - out <- cor_test(iris, "Petal.Length", "Petal.Width", method = "gaussian", bayesian = TRUE) + out <- cor_test( + iris, + "Petal.Length", + "Petal.Width", + method = "gaussian", + bayesian = TRUE + ) expect_equal(out$rho, 0.8620878, tolerance = 0.01) }) # Additional arguments ---------------------------------------------------- - test_that("cor_test one-sided p value", { - baseline <- cor.test(iris$Petal.Length, iris$Petal.Width, alternative = "greater") + baseline <- cor.test( + iris$Petal.Length, + iris$Petal.Width, + alternative = "greater" + ) out <- cor_test(iris, "Petal.Length", "Petal.Width", alternative = "greater") expect_equal(out$p, baseline$p.value, tolerance = 0.000001) @@ -199,6 +323,9 @@ test_that("cor_test one-sided p value", { # Edge cases -------------------------------------------------------------- test_that("cor_test 2 valid observations", { - out <- suppressWarnings(correlation(data.frame(v2 = c(2, 1, 1, 2), v3 = c(1, 2, NA, NA)))) + out <- suppressWarnings(correlation(data.frame( + v2 = c(2, 1, 1, 2), + v3 = c(1, 2, NA, NA) + ))) expect_true(is.na(out$r)) }) diff --git a/tests/testthat/test-cor_test_na_present.R b/tests/testthat/test-cor_test_na_present.R index 8449c265..92d49d1c 100644 --- a/tests/testthat/test-cor_test_na_present.R +++ b/tests/testthat/test-cor_test_na_present.R @@ -11,7 +11,11 @@ test_that("cor_test kendall", { skip_if_not_or_load_if_installed("ggplot2") out <- cor_test(ggplot2::msleep, "brainwt", "sleep_rem", method = "kendall") - out2 <- suppressWarnings(stats::cor.test(ggplot2::msleep$brainwt, ggplot2::msleep$sleep_rem, method = "kendall")) + out2 <- suppressWarnings(stats::cor.test( + ggplot2::msleep$brainwt, + ggplot2::msleep$sleep_rem, + method = "kendall" + )) expect_equal(out$tau, out2$estimate[[1]], tolerance = 0.001) expect_equal(out$p, out2$p.value[[1]], tolerance = 0.001) @@ -35,26 +39,58 @@ test_that("cor_test tetrachoric", { data$sleep_rem_binary <- as.numeric(data$sleep_rem > 1.2) # With Factors / Binary - expect_error(cor_test(data, "brainwt_binary", "sleep_rem_binary", method = "tetrachoric")) + expect_error(cor_test( + data, + "brainwt_binary", + "sleep_rem_binary", + method = "tetrachoric" + )) data$sleep_rem_ordinal <- as.factor(round(data$sleep_rem)) data$brainwt_ordinal <- as.factor(round(data$brainwt)) - out <- suppressWarnings(cor_test(data, "brainwt", "brainwt_ordinal", method = "polychoric")) + out <- suppressWarnings(cor_test( + data, + "brainwt", + "brainwt_ordinal", + method = "polychoric" + )) expect_equal(out$rho, 0.9999, tolerance = 0.01) # Biserial - expect_error(cor_test(data, "brainwt", "sleep_rem_binary", method = "pointbiserial")) - - expect_error(cor_test(data, "brainwt", "sleep_rem_binary", method = "biserial")) + expect_error(cor_test( + data, + "brainwt", + "sleep_rem_binary", + method = "pointbiserial" + )) + + expect_error(cor_test( + data, + "brainwt", + "sleep_rem_binary", + method = "biserial" + )) }) test_that("cor_test robust", { skip_if_not_or_load_if_installed("ggplot2") - out1 <- cor_test(ggplot2::msleep, "brainwt", "sleep_rem", method = "pearson", ranktransform = TRUE) - out2 <- cor_test(ggplot2::msleep, "brainwt", "sleep_rem", method = "spearman", ranktransform = FALSE) + out1 <- cor_test( + ggplot2::msleep, + "brainwt", + "sleep_rem", + method = "pearson", + ranktransform = TRUE + ) + out2 <- cor_test( + ggplot2::msleep, + "brainwt", + "sleep_rem", + method = "spearman", + ranktransform = FALSE + ) expect_equal(out1$r, out2$rho, tolerance = 0.01) }) @@ -75,7 +111,12 @@ test_that("cor_test percentage", { skip_if_not_or_load_if_installed("ggplot2") skip_if_not_or_load_if_installed("WRS2") - out <- cor_test(ggplot2::msleep, "brainwt", "sleep_rem", method = "percentage") + out <- cor_test( + ggplot2::msleep, + "brainwt", + "sleep_rem", + method = "percentage" + ) comparison <- WRS2::pbcor(ggplot2::msleep$brainwt, ggplot2::msleep$sleep_rem) expect_equal(out$r, as.numeric(comparison$cor), tolerance = 0.01) }) @@ -85,7 +126,12 @@ test_that("cor_test shepherd", { skip_if_not_or_load_if_installed("ggplot2") set.seed(333) - expect_error(cor_test(ggplot2::msleep, "brainwt", "sleep_rem", method = "shepherd")) + expect_error(cor_test( + ggplot2::msleep, + "brainwt", + "sleep_rem", + method = "shepherd" + )) }) @@ -121,19 +167,33 @@ test_that("cor_test gaussian", { expect_equal(out$r, -0.3679795, tolerance = 0.01) skip_if_not_or_load_if_installed("BayesFactor") - out <- cor_test(ggplot2::msleep, "brainwt", "sleep_rem", method = "gaussian", bayesian = TRUE) + out <- cor_test( + ggplot2::msleep, + "brainwt", + "sleep_rem", + method = "gaussian", + bayesian = TRUE + ) expect_equal(out$rho, -0.3269572, tolerance = 0.01) }) # Additional arguments ---------------------------------------------------- - test_that("cor_test one-sided p value", { skip_if_not_or_load_if_installed("ggplot2") - baseline <- cor.test(ggplot2::msleep$brainwt, ggplot2::msleep$sleep_rem, alternative = "greater") - - out <- cor_test(ggplot2::msleep, "brainwt", "sleep_rem", alternative = "greater") + baseline <- cor.test( + ggplot2::msleep$brainwt, + ggplot2::msleep$sleep_rem, + alternative = "greater" + ) + + out <- cor_test( + ggplot2::msleep, + "brainwt", + "sleep_rem", + alternative = "greater" + ) expect_equal(out$p, baseline$p.value, tolerance = 0.000001) }) diff --git a/tests/testthat/test-cor_to_pcor.R b/tests/testthat/test-cor_to_pcor.R index a256b14c..21b57512 100644 --- a/tests/testthat/test-cor_to_pcor.R +++ b/tests/testthat/test-cor_to_pcor.R @@ -9,7 +9,11 @@ test_that("pcor_to_cor", { pcormat <- summary(out, redundant = TRUE) ppcor <- ppcor::pcor(iris[1:4]) - expect_equal(max(as.matrix(pcormat[2:5]) - as.matrix(ppcor$estimate)), 0, tolerance = 0.01) + expect_equal( + max(as.matrix(pcormat[2:5]) - as.matrix(ppcor$estimate)), + 0, + tolerance = 0.01 + ) # TODO: fix # cormat <- pcor_to_cor(pcormat) @@ -22,9 +26,16 @@ test_that("pcor_to_cor", { # expect_equal(mean(p - hmisc$P, na.rm = TRUE), 0, tolerance = 0.001) # easycorrelation - cormat <- summary(pcor_to_cor(correlation(iris, partial = TRUE)), redundant = TRUE) - - expect_equal(max(as.matrix(cormat[2:5]) - as.matrix(cor(iris[1:4]))), 0, tolerance = 0.01) + cormat <- summary( + pcor_to_cor(correlation(iris, partial = TRUE)), + redundant = TRUE + ) + + expect_equal( + max(as.matrix(cormat[2:5]) - as.matrix(cor(iris[1:4]))), + 0, + tolerance = 0.01 + ) hmisc <- Hmisc::rcorr(as.matrix(iris[1:4]), type = c("pearson")) expect_equal(mean(as.matrix(cormat[2:5]) - hmisc$r), 0, tolerance = 0.0001) diff --git a/tests/testthat/test-cormatrix_to_excel.R b/tests/testthat/test-cormatrix_to_excel.R index 9fa24001..20afd229 100644 --- a/tests/testthat/test-cormatrix_to_excel.R +++ b/tests/testthat/test-cormatrix_to_excel.R @@ -1,6 +1,7 @@ test_that("cormatrix_to_excel select", { skip_if_not_or_load_if_installed("openxlsx2") - expect_snapshot(suppressWarnings(cormatrix_to_excel(mtcars, + expect_snapshot(suppressWarnings(cormatrix_to_excel( + mtcars, filename = "cormatrix1", overwrite = TRUE, p_adjust = "none", @@ -13,7 +14,8 @@ test_that("cormatrix_to_excel select", { test_that("cormatrix_to_excel p_adjust", { skip_if_not_or_load_if_installed("openxlsx2") - expect_snapshot(suppressWarnings(cormatrix_to_excel(airquality, + expect_snapshot(suppressWarnings(cormatrix_to_excel( + airquality, filename = "cormatrix1", overwrite = FALSE, p_adjust = "holm", diff --git a/tests/testthat/test-correlation.R b/tests/testthat/test-correlation.R index 9dc59c56..395aa67f 100644 --- a/tests/testthat/test-correlation.R +++ b/tests/testthat/test-correlation.R @@ -19,13 +19,16 @@ test_that("comparison with other packages", { p <- as.matrix(attributes(rez)$p[2:5]) expect_equal(mean(p - hmisc$P, na.rm = TRUE), 0, tolerance = 0.0001) - # Spearman out <- correlation(iris, include_factors = FALSE, method = "spearman") rez <- as.data.frame(summary(out, redundant = TRUE)) r <- as.matrix(rez[2:5]) - expect_equal(mean(r - cor(iris[1:4], method = "spearman")), 0, tolerance = 0.0001) + expect_equal( + mean(r - cor(iris[1:4], method = "spearman")), + 0, + tolerance = 0.0001 + ) hmisc <- Hmisc::rcorr(as.matrix(iris[1:4]), type = c("spearman")) expect_equal(mean(r - hmisc$r), 0, tolerance = 0.0001) @@ -38,7 +41,11 @@ test_that("comparison with other packages", { rez <- as.data.frame(summary(out, redundant = TRUE)) r <- as.matrix(rez[2:5]) - expect_equal(mean(r - cor(iris[1:4], method = "kendall")), 0, tolerance = 0.0001) + expect_equal( + mean(r - cor(iris[1:4], method = "kendall")), + 0, + tolerance = 0.0001 + ) # Biweight out <- correlation(iris, include_factors = FALSE, method = "biweight") @@ -53,7 +60,12 @@ test_that("comparison with other packages", { expect_equal(mean(r - cor(iris[1:2], iris[3:4])), 0, tolerance = 0.0001) # Partial - out <- correlation(mtcars, include_factors = FALSE, partial = TRUE, p_adjust = "none") + out <- correlation( + mtcars, + include_factors = FALSE, + partial = TRUE, + p_adjust = "none" + ) rez <- as.data.frame(summary(out, redundant = TRUE)) r <- as.matrix(rez[2:ncol(rez)]) @@ -77,9 +89,13 @@ test_that("comparison with other packages", { p <- bayestestR::pd_to_p(pd) expect_equal(mean(p - hmisc$P, na.rm = TRUE), 0, tolerance = 0.01) - # Bayesian - Partial - out <- correlation(iris, include_factors = FALSE, bayesian = TRUE, partial = TRUE) + out <- correlation( + iris, + include_factors = FALSE, + bayesian = TRUE, + partial = TRUE + ) rez <- as.data.frame(summary(out, redundant = TRUE)) r <- as.matrix(rez[2:5]) @@ -90,9 +106,14 @@ test_that("comparison with other packages", { p <- bayestestR::pd_to_p(pd) expect_equal(mean(abs(p - as.matrix(ppcor$p.value))), 0, tolerance = 0.001) - # Bayesian (Full) - Partial - out <- correlation(iris, include_factors = FALSE, bayesian = TRUE, partial = TRUE, partial_bayesian = TRUE) + out <- correlation( + iris, + include_factors = FALSE, + bayesian = TRUE, + partial = TRUE, + partial_bayesian = TRUE + ) rez <- as.data.frame(summary(out, redundant = TRUE)) r <- as.matrix(rez[2:5]) @@ -106,22 +127,47 @@ test_that("format checks", { skip_if_not_or_load_if_installed("psych") out <- correlation(iris, include_factors = TRUE) - expect_identical(c(nrow(summary(out, redundant = TRUE)), ncol(summary(out, redundant = TRUE))), c(7L, 8L)) + expect_identical( + c( + nrow(summary(out, redundant = TRUE)), + ncol(summary(out, redundant = TRUE)) + ), + c(7L, 8L) + ) expect_identical(c(nrow(summary(out)), ncol(summary(out))), c(6L, 7L)) expect_message( out <- correlation(iris, method = "auto", include_factors = TRUE), "Check your data" ) - expect_identical(c(nrow(summary(out, redundant = TRUE)), ncol(summary(out, redundant = TRUE))), c(7L, 8L)) + expect_identical( + c( + nrow(summary(out, redundant = TRUE)), + ncol(summary(out, redundant = TRUE)) + ), + c(7L, 8L) + ) expect_identical(c(nrow(summary(out)), ncol(summary(out))), c(6L, 7L)) - expect_true(all(c("Pearson correlation", "Point-biserial correlation", "Tetrachoric correlation") %in% out$Method)) + expect_true(all( + c( + "Pearson correlation", + "Point-biserial correlation", + "Tetrachoric correlation" + ) %in% + out$Method + )) # X and Y out <- correlation(iris[1:2], iris[3:4]) expect_identical(c(nrow(out), ncol(out)), c(4L, 11L)) - expect_identical(c(nrow(summary(out, redundant = TRUE)), ncol(summary(out, redundant = TRUE))), c(2L, 3L)) + expect_identical( + c( + nrow(summary(out, redundant = TRUE)), + ncol(summary(out, redundant = TRUE)) + ), + c(2L, 3L) + ) expect_identical(c(nrow(summary(out)), ncol(summary(out))), c(2L, 3L)) # Grouped @@ -132,7 +178,13 @@ test_that("format checks", { group_by(Species) %>% correlation(include_factors = TRUE) expect_identical(c(nrow(out), ncol(out)), c(18L, 12L)) - expect_identical(c(nrow(summary(out, redundant = TRUE)), ncol(summary(out, redundant = TRUE))), c(12L, 6L)) + expect_identical( + c( + nrow(summary(out, redundant = TRUE)), + ncol(summary(out, redundant = TRUE)) + ), + c(12L, 6L) + ) expect_identical(c(nrow(summary(out)), ncol(summary(out))), c(9L, 5L)) # pipe and select @@ -142,7 +194,13 @@ test_that("format checks", { select2 = c("Sepal.Length", "Sepal.Width") ) expect_identical(c(nrow(out), ncol(out)), c(2L, 11L)) - expect_identical(c(nrow(summary(out, redundant = TRUE)), ncol(summary(out, redundant = TRUE))), c(1L, 3L)) + expect_identical( + c( + nrow(summary(out, redundant = TRUE)), + ncol(summary(out, redundant = TRUE)) + ), + c(1L, 3L) + ) expect_identical(c(nrow(summary(out)), ncol(summary(out))), c(1L, 3L)) expect_equal(out[["r"]], c(0.8179, -0.3661), tolerance = 1e-2) expect_identical(out$Parameter1, c("Petal.Width", "Petal.Width")) @@ -152,7 +210,6 @@ test_that("format checks", { skip_if_not_or_load_if_installed("BayesFactor") skip_if_not_or_load_if_installed("lme4") - out <- correlation( iris, include_factors = TRUE, @@ -162,7 +219,13 @@ test_that("format checks", { partial_bayesian = TRUE ) expect_identical(c(nrow(out), ncol(out)), c(6L, 14L)) - expect_identical(c(nrow(summary(out, redundant = TRUE)), ncol(summary(out, redundant = TRUE))), c(4L, 5L)) + expect_identical( + c( + nrow(summary(out, redundant = TRUE)), + ncol(summary(out, redundant = TRUE)) + ), + c(4L, 5L) + ) expect_identical(c(nrow(summary(out)), ncol(summary(out))), c(3L, 4L)) }) @@ -176,7 +239,10 @@ test_that("specific types", { y = as.ordered(sample(letters[1:5], 20, TRUE)) ) - expect_warning(correlation(data, method = "polychoric"), regex = "It seems like") + expect_warning( + correlation(data, method = "polychoric"), + regex = "It seems like" + ) }) test_that("correlation doesn't fail when BFs are NA", { @@ -215,24 +281,26 @@ test_that("correlation output with zap_small", { test_that("missing values", { data <- mtcars - data[1,1] <- NA + data[1, 1] <- NA - r_pairwise <- stats::cor(data[,1:5], use = "pairwise") - r_complete <- stats::cor(data[,1:5], use = "complete") + r_pairwise <- stats::cor(data[, 1:5], use = "pairwise") + r_complete <- stats::cor(data[, 1:5], use = "complete") - corr_pairwise <- correlation(data[,1:5]) - corr_complete <- correlation(data[,1:5], missing = "keep_complete") + corr_pairwise <- correlation(data[, 1:5]) + corr_complete <- correlation(data[, 1:5], missing = "keep_complete") expect_equal(as.matrix(corr_pairwise), r_pairwise) expect_equal(as.matrix(corr_complete), r_complete) + r_pairwise <- stats::cor(data[, 1:2], data[, 3:5], use = "pairwise") + r_complete <- stats::cor(data[, 1:2], data[, 3:5], use = "complete") - - r_pairwise <- stats::cor(data[,1:2], data[,3:5], use = "pairwise") - r_complete <- stats::cor(data[,1:2], data[,3:5], use = "complete") - - corr_pairwise <- correlation(data[,1:2], data[,3:5]) - corr_complete <- correlation(data[,1:2], data[,3:5], missing = "keep_complete") + corr_pairwise <- correlation(data[, 1:2], data[, 3:5]) + corr_complete <- correlation( + data[, 1:2], + data[, 3:5], + missing = "keep_complete" + ) expect_equal(as.matrix(corr_pairwise), r_pairwise) expect_equal(as.matrix(corr_complete), r_complete) diff --git a/tests/testthat/test-display_print_dataframe.R b/tests/testthat/test-display_print_dataframe.R index 62465552..f50a0180 100644 --- a/tests/testthat/test-display_print_dataframe.R +++ b/tests/testthat/test-display_print_dataframe.R @@ -12,6 +12,15 @@ test_that("display and print method works - HTML", { skip_if(getRversion() < "4.0.0") skip_if_not_or_load_if_installed("gt") - expect_s3_class(display(correlation(subset(mtcars, select = c("wt", "mpg"))), format = "html"), "gt_tbl") - expect_s3_class(print_html(correlation(subset(mtcars, select = c("wt", "mpg")))), "gt_tbl") + expect_s3_class( + display( + correlation(subset(mtcars, select = c("wt", "mpg"))), + format = "html" + ), + "gt_tbl" + ) + expect_s3_class( + print_html(correlation(subset(mtcars, select = c("wt", "mpg")))), + "gt_tbl" + ) }) diff --git a/tests/testthat/test-methods.R b/tests/testthat/test-methods.R index 5b198a0e..12996330 100644 --- a/tests/testthat/test-methods.R +++ b/tests/testthat/test-methods.R @@ -9,5 +9,8 @@ test_that("summary.correlation - target column", { expect_snapshot(summary(correlation(ggplot2::msleep), target = "t")) expect_snapshot(summary(correlation(ggplot2::msleep), target = "df_error")) expect_snapshot(summary(correlation(ggplot2::msleep), target = "p")) - expect_error(summary(correlation(ggplot2::msleep), target = "not_a_column_name")) + expect_error(summary( + correlation(ggplot2::msleep), + target = "not_a_column_name" + )) }) diff --git a/tests/testthat/test-renaming.R b/tests/testthat/test-renaming.R index 6cb7d79e..fc82c8e9 100644 --- a/tests/testthat/test-renaming.R +++ b/tests/testthat/test-renaming.R @@ -1,19 +1,18 @@ test_that("renaming columns", { # should warn the user expect_warning({ - out <- correlation(anscombe, - select = c("x1", "x2"), - rename = "var1" - ) + out <- correlation(anscombe, select = c("x1", "x2"), rename = "var1") }) expect_snapshot(print(out)) - expect_snapshot(correlation(anscombe, + expect_snapshot(correlation( + anscombe, select = c("x1", "x2"), rename = c("var1", "var2") )) - expect_snapshot(correlation(anscombe, + expect_snapshot(correlation( + anscombe, select = c("x1", "x2"), select2 = c("y1", "y2"), rename = c("var1", "var2")