R/numberForLevels.R

Defines functions numberForLevels

Documented in numberForLevels

#'numberForLevels
#' @param dfCol a column of a data.frame object whose levels have to be numbered. Note that this is not a character string but the column itself (refer to examples)
#' @param vec1 a vector of class character containing the levels in column \code{dfCol}
#' @param vec2 a vector containing the values to be assigned to each level in \code{vec1}. 
#' @return numberForLevels returns a data.frame object containing one column where each entry of the original column is replaced by the number assigned for the respective level. NA column entries stay unaffected.
#' @description numberForLevels takes as input a column (\code{dfCol}), a character vector containing the levels of the column, and a numeric vector containing the numbers to be assigned to these levels and returns a one column data.frame object with each entry of the original column replaced by the number corresponding to the respective level. 
#' @examples
#' numberForLevels(table[,"col1"], c("a","b","c"),c(1:3))
#' numberForLevels(warpbreaks[,"tension"],c("L","M","H"),c(1,5,10))
#' numberForLevels(iris[,"Species"],c("setosa", "versicolor", "virginica"),c(101,102,103))
#' @export
numberForLevels<-function(dfCol,vec1,vec2)
{
  newCol<-data.frame(1:length(dfCol))				
  for (i in 1:length(vec1))								
  {
    newCol[which(dfCol[]==vec1[i]),]<-vec2[i]
    newCol[which(is.na(dfCol)),]<-NA
  }
  return(newCol)
}
lwTools/agriTrf documentation built on March 26, 2020, 12:09 a.m.