Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a table with multiple t-tests

I have over 150 t-tests between different groups in a study (with only like 25 variables being significant) but I still need to list out all the results for my thesis appendix.

Is there an easy way to combine each of the t-tests into 1 table?

Also, I know my method is inefficient, I couldn't figure out the for loop (if anyone would know how to do that with 2 databases)

Example of the t-tests.

t.test(Q8d3landowner$Q8_1, Q8d3rent$Q8_1, var.equal = TRUE)
t.test(Q8d3landowner$Q8_2, Q8d3rent$Q8_2, var.equal = TRUE)
t.test(Q8d3landowner$Q8_3, Q8d3rent$Q8_3, var.equal = TRUE)
t.test(Q8d3landowner$Q8_4, Q8d3rent$Q8_4, var.equal = TRUE)
t.test(Q8d3landowner$Q8_5, Q8d3rent$Q8_5, var.equal = TRUE)
t.test(Q8d3landowner$Q8_6, Q8d3rent$Q8_6, var.equal = TRUE)
t.test(Q8d3landowner$Q8_7, Q8d3rent$Q8_7, var.equal = TRUE)
t.test(Q8d3landowner$Q8_8, Q8d3rent$Q8_8, var.equal = TRUE)

t.test(Q8d3own$Q8_1, Q8d3rent$Q8_1, var.equal = TRUE)
t.test(Q8d3own$Q8_2, Q8d3rent$Q8_2, var.equal = TRUE)
t.test(Q8d3own$Q8_3, Q8d3rent$Q8_3, var.equal = TRUE)
t.test(Q8d3own$Q8_4, Q8d3rent$Q8_4, var.equal = TRUE)
t.test(Q8d3own$Q8_5, Q8d3rent$Q8_5, var.equal = TRUE)
t.test(Q8d3own$Q8_6, Q8d3rent$Q8_6, var.equal = TRUE)
t.test(Q8d3own$Q8_7, Q8d3rent$Q8_7, var.equal = TRUE)
t.test(Q8d3own$Q8_8, Q8d3rent$Q8_8, var.equal = TRUE)

Output example

Two Sample t-test

data:  Q8d3own$Q8_5 and Q8d3rent$Q8_5
t = 1.3478, df = 943, p-value = 0.178
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.04012354  0.21607738
sample estimates:
mean of x mean of y 
 2.884892  2.796915 
like image 217
Corrin Winter Avatar asked Jun 08 '26 14:06

Corrin Winter


1 Answers

You did not give us an reproducible example, so I will use some simulated data. You need to organize your data so you can use some form of loop:

test1 <- as.data.frame(matrix(as.numeric(NA), 15, 20))
test2 <- as.data.frame(matrix(as.numeric(NA), 15, 20))
  
for (i in 1:20) test1[, i] <- rnorm(15, 0, 1)
for (i in 1:20) test2[, i] <- rnorm(15, 0.5, 1)

# A function doing the t.test and collecting the results you want in the table

my.test <- function(x, y) { 
  l <- t.test(x, y, var.equal=TRUE)
  return(list(l$statistic, l$p.value)) # add the others you want in your table
}

res <- matrix(as.numeric(NA), 20, 2)

colnames(res) <- c("statistic", "p.value")

for (i in 1:20) res[i, ] <- unlist(my.test(test1[, i], test2[, i])) 

The matrix res now contains the results, and I leave the formatting for you.

like image 93
kjetil b halvorsen Avatar answered Jun 11 '26 07:06

kjetil b halvorsen