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

It wouldn’t be faster, but you can use outer to simplify the code. It does require a vectorized function, so here I’ve used Vectorize to make a vectorized version of the function to get the correlation between two columns. df <- data.frame(x=rnorm(100),y=rnorm(100),z=rnorm(100)) n <- ncol(df) corpij <- function(i,j,data) {cor.test(data[,i],data[,j])$p.value} corp <- Vectorize(corpij, vectorize.args=list(“i”,”j”)) outer(1:n,1:n,corp,data=df)

Idiomatic R code for partitioning a vector by an index and performing an operation on that partition

Yet another option is ave. For good measure, I’ve collected the answers above, tried my best to make their output equivalent (a vector), and provided timings over 1000 runs using your example data as an input. First, my answer using ave: ave(df$x, df$index, FUN = function(z) z/sum(z)). I also show an example using data.table package … Read more