Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I perform a pairwise t.test in R across multiple independent vectors?

Tags:

r

TL;DR edition

I have vectors X1,X2,X3,...Xn. I want to test to see whether the average value for any one vector is significantly different than the average value for any other vector, for every possible combination of vectors. I am seeking a better way to do this in R than running n^2 individual t.tests.

Full Story

I have a data frame full of census data for a particular CSA. Each row contains observations for each variable (column) for a particular census tract.

What I need to do is compare means for the same variable across census tracts in different MSAs. In other words, I want to factor my data.frame according to the MSA designation variable (which is one of the columns) and then compare the differences in the means for another variable of interest pairwise across each newly-factored MSA. This is essentially doing pairwise t.tests across each ensuing vector, but I wish to do this in a more elegant way than writing t.test(MSAx, MSAy) over and over again. How can I do this?

like image 365
Zelbinian Avatar asked Feb 07 '13 00:02

Zelbinian


1 Answers

The advantage to my method below to the one proposed by @ashkan would be that mine removes duplicates. (i.e. either X1 vs X2 OR X2 vs X1 will appear in the results, not both)

# Generate dummy data
df <- data.frame(matrix(rnorm(100), ncol = 10))
colnames(df) <- paste0("X", 1:10)

# Create combinations of the variables
combinations <- combn(colnames(df),2, simplify = FALSE)

# Do the t.test
results <- lapply(seq_along(combinations), function (n) {
                  df <- df[,colnames(df) %in% unlist(combinations[n])]
                  result <- t.test(df[,1], df[,2])
                  return(result)})

# Rename list for legibility    
names(results) <- paste(matrix(unlist(combinations), ncol = 2, byrow = TRUE)[,1], matrix(unlist(combinations), ncol = 2, byrow = TRUE)[,2], sep = " vs. ")
like image 92
R J Avatar answered Oct 13 '22 19:10

R J