R/assignColorToCondition.2.R

Defines functions assignColorToCondition.2

Documented in assignColorToCondition.2

#' Assign a random color to unique elements in a vector
#' 
#' This function assigns color to a unique cases in a vector. It also allows a supply of color palette in the form of vector of colors  which R will use assign colors to the condition, instead of being randomly selected.  
#' 
#' @param vec A character or factor vector which will be converted into colors
#' @param ColrVecProvided A boolean indicarting whether to use supplied color palette
#' @param ColorVec A character or factor vector of unique colors (palette)
#' @author Alexander Kheirallah ([email protected])
#' @export

assignColorToCondition.2 <- function(vec, ColrVecProvided=FALSE, ColorVec=NULL) {
  vec <- as.character(vec)
  uniqueElements <- unique(vec)
  ColorVec <- as.character(ColorVec)
  if(ColrVecProvided==FALSE){
    for( i in 1:length(uniqueElements)){
      vec[vec==uniqueElements[i]] <- colors()[sample(length(colors()),1)]
    }
  }
  else{
    if(length(ColorVec) < length(unique(vec))){
      stop("You have provided less colors than unique elements of vector. Make sure you have at least as many colors as unique elements of vector")
    }
    
    for( i in 1:length(uniqueElements)){
      currentColor <- ColorVec[sample(length(ColorVec),1)]
      vec[vec==uniqueElements[i]] <- currentColor
      ColorVec <- ColorVec[!(ColorVec==currentColor)] # removed already used color
    }
  }
return(vec)
}
msxakk89/dat documentation built on April 3, 2020, 5:39 p.m.