R/utils.R

Defines functions ewise_mean

Documented in ewise_mean

#' @name utils
#'
#' @title Utilities
#'
#' @description Utilities functions
#'
#' @param x,y Numeric vectors of the same length.
#' @param zero.substitute Logical. If TRUE zero values are substituted with
#'   corresponding non-missing values whether possible.
#' @inheritParams base::mean
#'
#' @return Numeric vector.
#'
#' @keywords internal
NULL


#' @describeIn utils Element-wise mean calculation.
ewise_mean <- function(x, y, na.rm = FALSE, zero.substitute = FALSE) {

	x <- as.numeric(x)
	y <- as.numeric(y)

	if (zero.substitute) {

		ewm <- dplyr::case_when(
			x == 0 & y == 0 ~ 0,
			x == 0 & y != 0 ~ y,
			x != 0 & y == 0 ~ x,
			TRUE ~ purrr::map2_dbl(x, y, ~ mean(c(.x,.y), na.rm = na.rm))
		)

	} else {

		ewm <- purrr::map2_dbl(x, y, ~ mean(c(.x,.y), na.rm = na.rm))

	}

	return(ewm)

}

Try the dispositionEffect package in your browser

Any scripts or data that you put into this service are public.

dispositionEffect documentation built on May 30, 2022, 9:05 a.m.