R/convertToLevels.R

Defines functions convertToLevels

Documented in convertToLevels

#'convertToLevels
#' @param dfCol a column of a data.frame object whose entries have to be cast into factor classes. Note that this is not a character string but the column itself (refer to examples).
#' @param numLevels an integer indicating the allowed number of different numeric values.
#' @param numBreaks an integer indicating the number of class divisions (or exact boundaries) that should be taken.
#' @return convertToLevels returns an object of class factor which contains the newly created levels (factor classes) from the entries in the column \code{dfCol}. 
#' @description convertToLevels takes as input a column (\code{dfCol}), the allowed number of levels (\code{numLevels}) for the column, and the number of class divisions (\code{numBreaks}) and casts the numeric entries of the column to factor classes. If the column \code{dfCol} is already of class factor then the column is returned as it is (see example 2 below). 
#' @examples
#' convertToLevels(iris[,"Sepal.Length"],4,5)
#' convertToLevels(iris[,"Species"],3,5)
#' @export
convertToLevels<-function(dfCol,numLevels,numBreaks)
{
  variable<-dfCol

  if(!is.factor(dfCol))
  {
  	if(length(levels(as.factor(dfCol)))<numLevels)
    {
    	variable<-as.factor(dfCol) 
    }
    else 
    {
    	variable<-cut(dfCol,breaks=numBreaks,include.lowest=T)
    }
  } 
  

  factorConverted<-as.factor(variable)   
  return(factorConverted)
}
lwTools/agriTrf documentation built on March 26, 2020, 12:09 a.m.