Improve this code by eliminating nested for cycles

蹲街弑〆低调 提交于 2019-12-23 18:20:42

问题


The R package corrplot contains, among the other stuff, this nifty function

cor.mtest <- function(mat, conf.level = 0.95){
  mat <- as.matrix(mat)
    n <- ncol(mat)
    p.mat <- lowCI.mat <- uppCI.mat <- matrix(NA, n, n)
    diag(p.mat) <- 0
    diag(lowCI.mat) <- diag(uppCI.mat) <- 1
    for(i in 1:(n-1)){
        for(j in (i+1):n){
            tmp <- cor.test(mat[,i], mat[,j], conf.level = conf.level)
            p.mat[i,j] <- p.mat[j,i] <- tmp$p.value
            lowCI.mat[i,j] <- lowCI.mat[j,i] <- tmp$conf.int[1]
            uppCI.mat[i,j] <- uppCI.mat[j,i] <- tmp$conf.int[2]
        }
    }
    return(list(p.mat, lowCI.mat, uppCI.mat))
}

which computes the p-values and confidence intervals for the pairwise correlations among variables x_1,...,x_n, given N observations of the n variables. The function takes a numeric matrix in input, and returns a list whose 3 elements are 3 nxn symmetric matrices: that's why, inside the nested for loops, only the upper diagonal parts of the 3 matrices are computed. Example:

res1 <- cor.mtest(mtcars,0.95)
> str(res1)
List of 3
 $ : num [1:11, 1:11] 0.00 6.11e-10 9.38e-10 1.79e-07 1.78e-05 ...
 $ : num [1:11, 1:11] 1 -0.926 -0.923 -0.885 0.436 ...
 $ : num [1:11, 1:11] 1 -0.716 -0.708 -0.586 0.832 ...

I think (and I may be wrong) that for loops are not very idiomatic in R: I see a lot of code where people substitute them with the map family of function from purr, or the apply family of function from base. I would like to eliminate the two for loops with such functional programming functions. Can you show me how to do it?

来源:https://stackoverflow.com/questions/42673081/improve-this-code-by-eliminating-nested-for-cycles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!