R/trim_z.R

Defines functions trim_z

Documented in trim_z

#' A Data Transformation Function
#'
#' This function will trim variables based on a certain range of zscores
#' @param x dataframe
#' @param variables c() of columns to trim
#' @param trim a single value z-score to use for trimming
#' @keywords trim
#' @export
#' @examples
#' composite_z.mean(x, variables = c(), name = "name")

trim_z <- function (x, variables = c(), trim = 3.5){
  trim.upper <- abs(trim)
  trim.lower <- abs(trim)*-1
  colnames(x) <- gsub(" ", ".", colnames(x))
  colorder <- colnames(x)
  variables <- gsub(" ", ".", variables)
  for (variable in colnames(x[,variables])){
    x <- transform(x, variable = scale(x[variable], center = TRUE, scale = TRUE))
    variablename <- paste(variable, "_z", sep = "")
    names(x)[length(x)] <- variablename
    x <- dplyr::mutate(x, variable = ifelse(get(variablename)<=trim.upper & get(variablename)>=trim.lower,get(variable),NA))
    x <- x[which(colnames(x)!=variable)]
    colnames(x)[which(colnames(x)=="variable")] <- variable
    x <- x[,-which(names(x) %in% variablename)]
  }
  x <- x[colorder]
  return(x)
}
dr-JT/datatransform documentation built on May 20, 2018, 2:35 a.m.