#' Carry out within-group centring.
#'
#' Calculate within-group effects based on methods of van de Pol and Wright.
#'
#' @param data Dataset in which within-group centring will be carried out.
#' N.B. First argument makes this function compatible with dplyr piping.
#' @param Variable An unquoted column name. The name of variable column on which centring will occur.
#' @param Group An unquoted column name. The name of grouping column.
#'
#' @return A tibble with two new columns containing within group mean and deviance.
#' @export
#' @import dplyr
#' @import rlang
#'
#' @examples
#' library(dplyr)
#'
#' dummy_dat <- tibble(group = rep(LETTERS[1:4], 20), value = runif(80, 0, 10))
#'
#' #Stand alone function
#' WG_centre(dummy_dat, value, group)
#'
#' #Inside dplyr pipe
#' dummy_dat %>%
#' #Merge two factor levels
#' rowwise() %>%
#' mutate(group = ifelse(group == "B", "A", group)) %>%
#' WG_centre(value, group)
#'
WG_centre <- function(data, Variable, Group){
#Define variables to avoid global variable warning
WGmean <- WGdev <- NULL
Variable <- enquo(Variable)
Group <- enquo(Group)
mean_name <- sym(paste0(as_name(Variable), "_WGmean"))
dev_name <- sym(paste0(as_name(Variable), "_WGdev"))
output <- data %>%
group_by(!!Group) %>%
mutate(WGmean = mean(!!Variable),
WGdev = !!Variable - WGmean) %>%
rename(!!mean_name := WGmean,
!!dev_name := WGdev)
return(output)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.