R/transform_data.R

#' Transform numeric data
#'
#' Transform numeric data for modelling and plotting
#' @param x Numeric vector to be transformed.
#' @param type The type of transformation to apply.
#' Can be 'standard': with a mean 0 and sd 1;
#' 'standard.log': with a mean 0 and sd 1 but all values > 0 to allows for future log transformation;
#' 'centre': mean of 0.
#'
#' @return Numeric vector with transformed values.
#' @export
#' @importFrom stats sd
#'
#' @examples
#'
#' #Mean 0 and sd 1
#' transform(mtcars$disp, type = "standard")

transform <- function(x, type = "standard"){

  if(type == "standard"){

    output <- (x - mean(x))/sd(x)

  } else if(type == "standard.log"){

    #This standardises to have a sd = 1. However, we move the mean so that all values >0.
    #This is necessary if you also need to look at logarithmic relationships.
    output <- ((x - mean(x)) / sd(x)) -  min((x - mean(x)) / sd(x)) + 1

  } else if(type == "centre" | type == "center"){

    output <- x - mean(x)

  } else {

    stop("type must be either standard, standard.log, or centre.")

  }

  return(output)

}


#' Reverse previous transformations.
#'
#' Reverse transformations applied by the 'transform' function.
#' Can be applied to a numeric vector of any length.
#' @param x Numeric vector of values to be backtransformed.
#' @param y Numeric vector of original data before transformation.
#' @param type The type of transformation to apply.
#' Can be 'standard': with a mean 0 and sd 1;
#' 'standard.log': with a mean 0 and sd 1 but all values > 0 to allows for future log transformation;
#' 'centre': mean of 0.
#'
#' @return A numeric vector of back-transformed data.
#' @export
#'
#' @examples
#'
#' #Transform data with mean 0 and sd 1.
#' transform_data <- transform(mtcars$disp, type = "standard")
#'
#' #Back transform all data to the original format
#' back.transform(x = transform_data, y = mtcars$disp, type = "standard")
#'
#' #Back transform single value to the original format
#' back.transform(x = 0, y = mtcars$disp, type = "standard")

back.transform <- function(x, y, type = "standard"){

  if(type == "standard"){

    output <- (x*sd(y)) + mean(y)

  } else if(type == "standard.log"){

    output <- ((x - 1 + min((y - mean(y))/sd(y)))*sd(y)) + mean(y)

  } else if(type == "centre" | type == "center"){

    output <- x + mean(y)

  } else {

    stop("type must be either standard, standard.log, or centre.")

  }

  return(output)

}
LiamDBailey/MyFuncs documentation built on June 5, 2019, 5:10 p.m.