#Average Frequency
#NA's are removed but digits that represent particular NA's need to be removed before
#using this function.
#' Average frequency of numbers in a column
#'
#' The 'average_fre()' function takes a column in a data frame and
#' calculates the average frequency with which integers are
#' paired with numbers in the first decimal place.
#'
#'To calculate average frequency, the number of times each pair (integer and first decimal)
#'occurs is calculated. This number appears once in the numerator for each
#'occurrence. These numbers are summed and divided by n.
#'
#'For example, for the vector c(1.4, 0.4, 1.4, 2.0) the average frequency is calculated by
#'(2 + 1 + 2 + 1) / 4 = 1.5.
#'
#' @param data A data frame
#' @param variable A numeric variable that includes the first decimal place.
#' @param group A second variable used to group the primary variable such that average frequency is calculated separately for each group.
#' @param decimal_place The number of decimal places used for the calculation.
#' The default is set to "1" meaning decimals in the second (hundreds place)
#' and below are discarded.
#'
#' @return A numeric value or when a group variable is specified a vector of numeric values.
#' @export
#'
#' @examples
#' average_fre(simulated_normal, obs)
#'
#' @importFrom magrittr %>%
#' @importFrom rlang .data
average_fre <- function(data, variable, group = NULL, decimal_place = 1) {
#Need to figure out how to use something like this:
#if(class(data{variable}) != "numeric") {stop("average_fre() will only function on a numeric variable")}
if(data %>%
dplyr::summarise(class = class({{ variable }})) %>%
dplyr::pull() != "numeric") {stop("average_fre() will only function on a numeric variable")}
data %>%
dplyr::filter(!is.na({{ variable }})) %>%
dplyr::mutate(var = trunc({{ variable }} * 10^{{ decimal_place }})) %>%
dplyr::group_by({{ group }}, .data$var) %>%
dplyr::summarize(n = dplyr::n()) %>%
dplyr::mutate(total = .data$n * .data$n) %>%
dplyr::summarize(af = sum(.data$total) / sum(.data$n))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.