Is there a R function that applies a function to each pair of columns?

后端 未结 4 2123
小鲜肉
小鲜肉 2020-11-27 05:35

I often need to apply a function to each pair of columns in a dataframe/matrix and return the results in a matrix. Now I always write a loop to do this. For instance, to mak

4条回答
  •  无人及你
    2020-11-27 06:02

    You can use mapply, but as the other answers state its unlikely to be much faster as most of the time is being used up by cor.test.

    matrix(mapply(function(x,y) cor.test(df[,x],df[,y])$p.value,rep(1:3,3),sort(rep(1:3,3))),nrow=3,ncol=3)
    

    You could reduce the amount of work mapply does by using the symmetry assumption and noting the zero diagonal, eg

    v <- mapply(function(x,y) cor.test(df[,x],df[,y])$p.value,rep(1:2,2:1),rev(rep(3:2,2:1)))
    m <- matrix(0,nrow=3,ncol=3)
    m[lower.tri(m)] <- v
    m[upper.tri(m)] <- v
    

提交回复
热议问题