Skip to content

Commit

Permalink
Code style (#606)
Browse files Browse the repository at this point in the history
* lintr etc

* docs

* code style

* lintr

* code style

* rd

* format_alerts

* fix vignette

* problematic links
  • Loading branch information
strengejacke committed Jun 28, 2023
1 parent 798f2e7 commit 01cdbd1
Show file tree
Hide file tree
Showing 25 changed files with 268 additions and 194 deletions.
2 changes: 1 addition & 1 deletion R/bayesfactor_models.R
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,7 @@ as.matrix.bayesfactor_models <- function(x, ...) {

# Else... Get marginal likelihood
if (verbose) {
message("Computation of Marginal Likelihood: estimating marginal likelihood, please wait...")
insight::format_alert("Computation of Marginal Likelihood: estimating marginal likelihood, please wait...")
}
# Should probably allow additional arguments such as reps or cores to for bridge_sampler
bridgesampling::bridge_sampler(mod, silent = TRUE)
Expand Down
2 changes: 1 addition & 1 deletion R/bayesfactor_parameters.R
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ bayesfactor_pointnull <- function(posterior,
verbose = TRUE,
...) {
if (length(null) > 1 && verbose) {
message("'null' is a range - computing a ROPE based Bayes factor.")
insight::format_alert("`null` is a range - computing a ROPE based Bayes factor.")
}

bayesfactor_parameters(
Expand Down
2 changes: 0 additions & 2 deletions R/describe_posterior.R
Original file line number Diff line number Diff line change
Expand Up @@ -499,8 +499,6 @@ describe_posterior.default <- function(posteriors, ...) {
row.names(out) <- NULL
}



# Prepare output
attr(out, "ci_method") <- ci_method
out
Expand Down
16 changes: 11 additions & 5 deletions R/map_estimate.R
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
#' Maximum A Posteriori probability estimate (MAP)
#'
#' Find the **Highest Maximum A Posteriori probability estimate (MAP)** of a posterior, i.e., the value associated with the highest probability density (the "peak" of the posterior distribution). In other words, it is an estimation of the *mode* for continuous parameters. Note that this function relies on [estimate_density], which by default uses a different smoothing bandwidth (`"SJ"`) compared to the legacy default implemented the base R [density] function (`"nrd0"`).
#' Find the **Highest Maximum A Posteriori probability estimate (MAP)** of a
#' posterior, i.e., the value associated with the highest probability density
#' (the "peak" of the posterior distribution). In other words, it is an estimation
#' of the *mode* for continuous parameters. Note that this function relies on
#' [`estimate_density()`], which by default uses a different smoothing bandwidth
#' (`"SJ"`) compared to the legacy default implemented the base R [`density()`]
#' function (`"nrd0"`).
#'
#' @inheritParams hdi
#' @inheritParams estimate_density
#'
#' @return A numeric value if `x` is a vector. If `x` is a model-object,
#' returns a data frame with following columns:
#' \itemize{
#' \item `Parameter` The model parameter(s), if `x` is a model-object. If `x` is a vector, this column is missing.
#' \item `MAP_Estimate` The MAP estimate for the posterior or each model parameter.
#' }
#'
#' - `Parameter`: The model parameter(s), if `x` is a model-object. If `x` is a
#' vector, this column is missing.
#' - `MAP_Estimate`: The MAP estimate for the posterior or each model parameter.
#'
#' @examples
#' \dontrun{
Expand Down
4 changes: 2 additions & 2 deletions R/mediation.R
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ mediation.stanmvreg <- function(model, treatment, mediator, response = NULL, cen
# check for binary response. In this case, user should rescale variables
modelinfo <- insight::model_info(model)
if (any(sapply(modelinfo, function(i) i$is_binomial, simplify = TRUE))) {
message("One of moderator or outcome is binary, so direct and indirect effects may be on different scales. Consider rescaling model predictors, e.g. with `effectsize::standardize()`.")
insight::format_alert("One of moderator or outcome is binary, so direct and indirect effects may be on different scales. Consider rescaling model predictors, e.g. with `effectsize::standardize()`.")
}

# model responses
Expand Down Expand Up @@ -355,7 +355,7 @@ print.bayestestR_mediation <- function(x, digits = 3, ...) {
)

if (any(prop_mediated_ori$Estimate < 0)) {
message("\nDirect and indirect effects have opposite directions. The proportion mediated is not meaningful.")
insight::format_alert("\nDirect and indirect effects have opposite directions. The proportion mediated is not meaningful.")
}
}

Expand Down
2 changes: 1 addition & 1 deletion R/p_direction.R
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ p_direction.get_predicted <- function(x, ...) {
if ("iterations" %in% names(attributes(x))) {
out <- p_direction(as.data.frame(t(attributes(x)$iterations)), ...)
} else {
stop("No iterations present in the output.", call. = FALSE)
insight::format_error("No iterations present in the output.")
}
attr(out, "object_name") <- insight::safe_deparse_symbol(substitute(x))
out
Expand Down
9 changes: 8 additions & 1 deletion R/plot.R
Original file line number Diff line number Diff line change
Expand Up @@ -46,42 +46,49 @@ plot.bayestestR_eti <- function(x, ...) {
NextMethod()
}


#' @export
plot.bayestestR_si <- function(x, ...) {
insight::check_if_installed("see", "to plot support intervals")
NextMethod()
}


#' @export
plot.bayesfactor_parameters <- function(x, ...) {
insight::check_if_installed("see", "to plot Savage-Dickey Bayes factor")
NextMethod()
}


#' @export
plot.bayesfactor_models <- function(x, ...) {
insight::check_if_installed("see", "to plot models' Bayes factors")
NextMethod()
}


#' @export
plot.estimate_density <- function(x, ...) {
insight::check_if_installed("see", "to plot densities")
NextMethod()
}


#' @export
plot.estimate_density_df <- function(x, ...) {
insight::check_if_installed("see", "to plot models' densities")
NextMethod()
}


#' @export
plot.p_significance <- function(x, ...) {
insight::check_if_installed("see", "to plot practical significance")
NextMethod()
}


#' @export
plot.describe_posterior <- function(x, stack = FALSE, ...) {
insight::check_if_installed("see", "to plot posterior samples")
Expand All @@ -91,6 +98,6 @@ plot.describe_posterior <- function(x, stack = FALSE, ...) {
graphics::plot(estimate_density(model), stack = stack, ...) +
ggplot2::labs(title = "Posterior Samples", x = NULL, y = NULL)
} else {
warning(insight::format_message("Could not find model-object. Try ' plot(estimate_density(model))' instead."), call. = FALSE)
insight::format_warning("Could not find model-object. Try `plot(estimate_density(model))` instead.")
}
}
91 changes: 58 additions & 33 deletions R/point_estimate.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,22 @@
#'
#' Compute various point-estimates, such as the mean, the median or the MAP, to describe posterior distributions.
#'
#' @param centrality The point-estimates (centrality indices) to compute. Character (vector) or list with one or more of these options: `"median"`, `"mean"`, `"MAP"` or `"all"`.
#' @param dispersion Logical, if `TRUE`, computes indices of dispersion related to the estimate(s) (`SD` and `MAD` for `mean` and `median`, respectively).
#' @param threshold For `centrality = "trimmed"` (i.e. trimmed mean), indicates the fraction (0 to 0.5) of observations to be trimmed from each end of the vector before the mean is computed.
#' @param centrality The point-estimates (centrality indices) to compute. Character
#' (vector) or list with one or more of these options: `"median"`, `"mean"`, `"MAP"`
#' (see [`map_estimate()`]), `"trimmed"` (which is just `mean(x, trim = threshold)`),
#' `"mode"` or `"all"`.
#' @param dispersion Logical, if `TRUE`, computes indices of dispersion related
#' to the estimate(s) (`SD` and `MAD` for `mean` and `median`, respectively).
#' Dispersion is not available for `"MAP"` or `"mode"` centrality indices.
#' @param threshold For `centrality = "trimmed"` (i.e. trimmed mean), indicates
#' the fraction (0 to 0.5) of observations to be trimmed from each end of the
#' vector before the mean is computed.
#' @param ... Additional arguments to be passed to or from methods.
#' @inheritParams hdi
#'
#' @references Makowski, D., Ben-Shachar, M. S., Chen, S. H. A., and Lüdecke, D. (2019). *Indices of Effect Existence and Significance in the Bayesian Framework*. Frontiers in Psychology 2019;10:2767. \doi{10.3389/fpsyg.2019.02767}
#' @references Makowski, D., Ben-Shachar, M. S., Chen, S. H. A., and Lüdecke, D.
#' (2019). *Indices of Effect Existence and Significance in the Bayesian Framework*.
#' Frontiers in Psychology 2019;10:2767. \doi{10.3389/fpsyg.2019.02767}
#'
#' @note There is also a [`plot()`-method](https://easystats.github.io/see/articles/bayestestR.html) implemented in the \href{https://easystats.github.io/see/}{\pkg{see}-package}.
#'
Expand Down Expand Up @@ -59,13 +68,15 @@ point_estimate <- function(x, ...) {

#' @export
point_estimate.default <- function(x, ...) {
stop(insight::format_message(paste0("'point_estimate()' is not yet implemented for objects of class '", class(x)[1], "'.")), call. = FALSE)
insight::format_error(
paste0("'point_estimate()' is not yet implemented for objects of class '", class(x)[1], "'.")
)
}


#' @rdname point_estimate
#' @export
point_estimate.numeric <- function(x, centrality = "all", dispersion = FALSE, threshold = .1, ...) {
point_estimate.numeric <- function(x, centrality = "all", dispersion = FALSE, threshold = 0.1, ...) {
centrality <- match.arg(tolower(centrality), c("median", "mean", "map", "trimmed", "mode", "all"), several.ok = TRUE)
if ("all" %in% centrality) {
estimate_list <- c("median", "mean", "map")
Expand Down Expand Up @@ -119,15 +130,8 @@ point_estimate.numeric <- function(x, centrality = "all", dispersion = FALSE, th
}


.mode_estimate <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}



#' @export
point_estimate.data.frame <- function(x, centrality = "all", dispersion = FALSE, threshold = .1, ...) {
point_estimate.data.frame <- function(x, centrality = "all", dispersion = FALSE, threshold = 0.1, ...) {
x <- .select_nums(x)

if (ncol(x) == 1) {
Expand All @@ -148,8 +152,14 @@ point_estimate.data.frame <- function(x, centrality = "all", dispersion = FALSE,


#' @export
point_estimate.draws <- function(x, centrality = "all", dispersion = FALSE, threshold = .1, ...) {
point_estimate(.posterior_draws_to_df(x), centrality = centrality, dispersion = dispersion, threshold = threshold, ...)
point_estimate.draws <- function(x, centrality = "all", dispersion = FALSE, threshold = 0.1, ...) {
point_estimate(
.posterior_draws_to_df(x),
centrality = centrality,
dispersion = dispersion,
threshold = threshold,
...
)
}

#' @export
Expand Down Expand Up @@ -186,16 +196,25 @@ point_estimate.BGGM <- point_estimate.bcplm
#' @export
point_estimate.bamlss <- function(x, centrality = "all", dispersion = FALSE, component = c("conditional", "location", "all"), ...) {
component <- match.arg(component)
out <- point_estimate(insight::get_parameters(x, component = component), centrality = centrality, dispersion = dispersion, ...)
out <- .add_clean_parameters_attribute(out, x)
out
out <- point_estimate(
insight::get_parameters(x, component = component),
centrality = centrality,
dispersion = dispersion,
...
)
.add_clean_parameters_attribute(out, x)
}


#' @export
point_estimate.MCMCglmm <- function(x, centrality = "all", dispersion = FALSE, ...) {
nF <- x$Fixed$nfl
point_estimate(as.data.frame(x$Sol[, 1:nF, drop = FALSE]), centrality = centrality, dispersion = dispersion, ...)
point_estimate(
as.data.frame(x$Sol[, 1:nF, drop = FALSE]),
centrality = centrality,
dispersion = dispersion,
...
)
}


Expand All @@ -212,17 +231,6 @@ point_estimate.emmGrid <- function(x, centrality = "all", dispersion = FALSE, ..
point_estimate.emm_list <- point_estimate.emmGrid


# Helper ------------------------------------------------------------------



#' @keywords internal
.point_estimate_models <- function(x, effects, component, parameters, centrality = "all", dispersion = FALSE, ...) {
out <- point_estimate(insight::get_parameters(x, effects = effects, component = component, parameters = parameters), centrality = centrality, dispersion = dispersion, ...)
out
}


#' @rdname point_estimate
#' @export
point_estimate.stanreg <- function(x, centrality = "all", dispersion = FALSE, effects = c("fixed", "random", "all"), component = c("location", "all", "conditional", "smooth_terms", "sigma", "distributional", "auxiliary"), parameters = NULL, ...) {
Expand Down Expand Up @@ -294,7 +302,6 @@ point_estimate.sim.merMod <- function(x, centrality = "all", dispersion = FALSE,
}



#' @export
point_estimate.sim <- function(x, centrality = "all", dispersion = FALSE, parameters = NULL, ...) {
out <- .point_estimate_models(
Expand All @@ -314,7 +321,6 @@ point_estimate.sim <- function(x, centrality = "all", dispersion = FALSE, parame
}



#' @rdname point_estimate
#' @export
point_estimate.BFBayesFactor <- function(x, centrality = "all", dispersion = FALSE, ...) {
Expand All @@ -341,3 +347,22 @@ point_estimate.get_predicted <- function(x, ...) {
as.numeric(x)
}
}


# Helper ------------------------------------------------------------------

#' @keywords internal
.point_estimate_models <- function(x, effects, component, parameters, centrality = "all", dispersion = FALSE, ...) {
point_estimate(
insight::get_parameters(x, effects = effects, component = component, parameters = parameters),
centrality = centrality,
dispersion = dispersion,
...
)
}

#' @keywords internal
.mode_estimate <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
6 changes: 3 additions & 3 deletions R/reshape_iterations.R
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ reshape_iterations <- function(x, prefix = c("draw", "iter", "iteration", "sim")
prefix <- prefix[min(which(sapply(tolower(prefix), function(prefix) sum(grepl(prefix, tolower(names(x)), fixed = TRUE)) > 1)))]

if (is.na(prefix) || is.null(prefix)) {
stop(insight::format_message(
insight::format_error(
"Couldn't find columns corresponding to iterations in your dataframe, please specify the correct prefix."
), call. = FALSE)
)
}

# Get column names
Expand All @@ -58,7 +58,7 @@ reshape_iterations <- function(x, prefix = c("draw", "iter", "iteration", "sim")
)
row.names(long) <- NULL

class(long) <- class(long)[which(class(long) == "data.frame"):length(class(long))]
class(long) <- class(long)[which(inherits(long, "data.frame")):length(class(long))]
long
}

Expand Down
Loading

0 comments on commit 01cdbd1

Please sign in to comment.