R/splitlevel.R

#' @title Split a factor level based on another factor
#' @description Split a factor level based on another factor in a data.frame.
#' If you want to split a factor level based on a numerical variable,
#' first create a new factor level corresponding to the conditioning of your
#' numerical variable, then use 'splitlevel' to create a factor with the split
#' level.Look at the examples in the vignette for usage.
#'
#' @param data Input data-frame
#' @param splitfactor Factor to be split
#' @param splitlev The level in this factor to be split
#' @param factorby The factor on which to split based on
#' @param newfactorname The name of the new split factor level
#'
#' @return data.frame
#' @export
#' @examples
#' x <- data.frame(first = c(1:20), second = rep(c("A","B"), each = 10), third = rep_len(c("W","X","Y","Z"), 20))
#' splitlevel(x,"second","A","third", "callitwhatyouwant")
splitlevel <-function(data, splitfactor, splitlev , factorby, newfactorname = "splitfactor") {

# Check if input classes match expectations
        if(!is.data.frame(data)) {
                stop('The input "data" is not of the class data frame!\n',
                'You have provided an object of class: ', class(data))
        }
        if(!is.character(splitfactor)) {
                stop('The input "splitfactor" is not of the class character!\n',
                     'You have provided an object of class: ', class(splitfactor))
        }
        if(!is.element(splitlev,levels(data[,splitfactor]))) {
                stop('The input "splitlev" is not a level in "splitfactor"!\n')
        }
        if(!is.character(factorby)) {
                stop('The input "factorby" is not of the class character!\n',
                     'You have provided an object of class: ', class(factorby))
        }
        if(!is.character(newfactorname)) {
                stop('The input "newfactorname" is not of the class character!\n',
                     'You have provided an object of class: ', class(newfactorname))
        }

# Check if splitfactor and factorby are a part of data
        if(!is.element(splitfactor, names(data))) {
                stop('The input "splitfactor" is not part of data!')
        }
        if(!is.element(factorby, names(data))) {
                stop('The input "factorby" is not part of data!')
        }

# Split level

        data[[newfactorname]] <- data[,splitfactor]
        data[[newfactorname]] <- ifelse(as.character(data[,splitfactor])==splitlev,
                                    paste(as.character(data[,splitfactor]),
                                          as.character(data[,factorby]),sep='_'),
                                    as.character(data[,splitfactor]))
        data
}
KPdir/foofactors documentation built on May 8, 2019, 4:41 p.m.