Skip to content

Instantly share code, notes, and snippets.

@sckott
Created May 12, 2011 12:26
Show Gist options
  • Save sckott/968408 to your computer and use it in GitHub Desktop.
Save sckott/968408 to your computer and use it in GitHub Desktop.
Function for calculating pairwise correlations between b*c columns of data in a data frame
# a = data frame
# b = list of variables in x
# c = list of variables in y
# method_ = one of pearson, spearman, kendall (or their abbreviations)
# output is a data frame with as many columns as b * c
GetCorrs <- function(a, b, c, method_) {
dfout_ <- list()
names <- list()
names_ <- list()
for(i in 1:length(b)) {
dfout <- data.frame(r = rep(NA, length(c)), P = rep(NA, length(c)))
for(j in 1:length(c)) {
rout <- cor.test(a[, b[i]], a[, c[j]], alternative = "two.sided", method = method_)
dfout[j, ] <- c(as.numeric(rout[[4]]), as.numeric(rout[[3]]))
names[[j]] <- paste(names(a)[b[i]], names(a)[c[j]], sep="_")
}
dfout_[[i]] <- dfout
names_[[i]] <- names
}
dfout_df <- do.call(rbind, dfout_)
dfout_df$traits <- as.vector(sapply(names_, function(x) laply(x, identity)))
return(dfout_df)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment