R/CV.R

Defines functions CV rowCV bootRowCV downSampleRowCV

N_MC_CORE <- 16
# CV
CV <- function(x) sd(x) / mean(x)

# CV of each row in a matrix
rowCV <- function(xp){
    rowMeans <- Matrix::rowMeans
    m <- rowMeans(xp)
    s <- apply(xp, 1, sd)
    s/m
}

# CI of CV of each row in a matrix
bootRowCV <- function(x, rep = 1000){
    cvs <- mclapply(seq_len(rep), function(i){
        xp <- x[, sample(ncol(x), ncol(x), replace = TRUE)]
        rowCV(xp)
    }, mc.cores = N_MC_CORE)
    cvs <- do.call(cbind, cvs)
    
    cv0 <- rowCV(x)
    res <- apply(cvs, 1, quantile, probs = c(0.025, 0.975), na.rm = TRUE)
    rownames(res) <- c('lower', 'upper')
    res <- cbind(cv = cv0, t(res))
    return(res)
}

# downsampling CV of each row in a matrix
downSampleRowCV <- function(x, k, n){
    res <- mclapply(seq_len(n), function(i){
        xp <- x[, sample(seq_len(ncol(x)), k)]
        m <- Matrix::rowMeans(xp)
        sd <- apply(xp, 1, sd)
        res <- sd / m
    }, mc.cores = N_MC_CORE)
    res <- do.call(cbind, res)
    return(res)
}
mt1022/Rutils documentation built on May 25, 2019, 10:34 p.m.