R/ratio.R

Defines functions ratio

Documented in ratio

#'  imputate data
#'
#'
#' @param data  A data frame
#' @param numer numerator of ratio, a vector
#' @param denom denominator of ratio, a vector
#' @param newName  new name for ratio, a vector
#'
#' @examples
#' dat <- data.frame(a = c(1:10),b=c(2:11),c=c(11:20),d=c(1:10))
#' rat <- data.frame(numer=c("a","b"),denom=c("c","d"))
#' ratio(dat,rat$numer,rat$denom)
#'
#' @name ratio
#' @rdname ratio
#' @export
#'

ratio <- function(data,
                  numer=NULL,
                  denom=NULL,
                  newName= NULL
)
{
    totalVar <- names(data);
    # detect whether the variable is exist in raw data variables
    if(length(numer)!=length(denom))
    {
        stop("Error, there must be equal numbers in old and new ")
    }

    numer <- as.character(numer);
    denom <- as.character(denom);
    newName <- as.character(newName);
    for (i in c(numer,denom)){
        if (!(i %in% (totalVar))){
            stop( paste(i,' is not exist in raw data, please recheck it'));
        }
    }
    for(i in 1:length(numer)){
        tmpNumer <- numer[i];
        tmpDenom <- denom[i];
        tmpNewName <- newName[i];
            if (is.na(tmpNewName)){
                warning('There is no new name to nominate ratio. Use default name "numerator/denominator"');
                tmpNewName <- as.character(paste0(tmpNumer,'_by_',tmpDenom));
            }
        data[tmpNewName] <- data[tmpNumer] / data[tmpDenom];
    }
    return(data)
}
ShouyeLiu/metaboliteUtility documentation built on May 6, 2019, 9:07 a.m.