R/reshape.R

Defines functions reshape

Documented in reshape

#' Data Transformation Function
#'
#' This function is an extension of the spread() function in tidyverse.
#' It can multiple values to apply spread() on.
#' @param x dataframe
#' @param key The variable used for spreading
#' @param values A vector of columns that contain the values
#' @param by What column is not being reorganized and needs to be preserved. Usually "Subject"
#' @keywords reshape
#' @export
#' @examples
#' reshape(x, key = "variable", values = c("value1", "value2"), by = "Subject")

reshape <- function(x, key = key, values = c(), by = ""){
  if (by==""){
    y <- data.frame(placeholder = 1)
    for (value in values){
      z <- dplyr::select(x, key, value)
      z <- tidyr::spread(z, key = key, value = value)
      colnames(z) <- paste(colnames(z), value, sep = "_")
      y <- cbind(y, z)
    }
    y <- dplyr::select(y, -placeholder)
  } else {
    y <- data.frame(by = numeric(0))
    colnames(y) <- by
    for (value in values){
      z <- dplyr::select(x, by, key, value)
      z <- tidyr::spread(z, key = key, value = value)
      colnames(z)[which(colnames(z)!=by)] <- paste(colnames(z)[which(colnames(z)!=by)],
                                                   value, sep = "_")
      y <- full_join(y, z, by = by)
    }
  }
  return(y)
}
dr-JT/datatransform documentation built on May 20, 2018, 2:35 a.m.