Dirigible Dirigible - 1 year ago 48
R Question

How to run all "N take 2" iterations of a function?

I've written a simple correlation function that takes in three variables. "A" and "B" are numerical vectors of equal length, and "n" is the length.

Corr.fxn <- function(A, B, n){
Correlation <- (sum((A - mean(A))*(B - mean(B))) / (n-1)) / (sd(A)*sd(B))

The function works well enough, but I have many vectors I want to process. What's the best way to modify this code to process all "N take 2" unique analyses for my set of vectors "N"?


Example data showing the structure of the vectors:

A <- c(-1, 0, 1, -1, 0, 1, -1, 0, 1)
B <- c(1, 1, -1, 0, 1, -1, 0, 0, 1)
n <- length(A)

So let's say I have vectors A through Z and I want to modify my code to output a new vector containing all {26 take 2} correlation values.

Answer Source

Here is one possible way you can do it assuming you have a bunch of numeric vectors in a list v as follows:

v <- list()
for (i in 1:10) {
  v[[i]] <- sample(1:10, 10, replace = TRUE)

apply(combn(1:10, 2), 2, function(x) Corr.fxn(v[[x[1]]], v[[x[2]]], length(v[[x[1]]])))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download