user3062260
user3062260

Reputation: 1644

t-tests on different groups by iteration in R

I have a group of patient scores such as:

 P1 <- c(7.81,6.93,7.11)
 P2 <- c(8.61,7.95,8.11)
 P3 <- c(8.41,7.65,7.01)
 ....etc

I have a big group of healthy people scores such as:

 HC <- c(5.22,4.87,6.93,5.27,6.01,4.55,.....etc)

I have listed the names of patients in a vector:

 patients <- c('P1','P2','P3',....etc)

I am trying to perform t-tests for each of the patient scores against the healthy control group. I have written:

 for (i in patients){t.test(patients[i],HC)}

I was expecting R to print the result of a load of t-tests to the console but it tells me:

 Error in t.test.default(patients[i], HC) : 
 not enough 'x' observations
 In addition: Warning message:
 In mean.default(x) : argument is not numeric or logical: returning NA

I just need to get some P-values on the data and think this may be a simple syntax problem but don't work much with R and can't seem to find a quick answer. Any help would be great?

Upvotes: 0

Views: 2064

Answers (2)

CT Zhu
CT Zhu

Reputation: 54390

Use a list for patients containing the actual vectors, rather than the names of the vectors:

> patients <- list(P1, P2, P3)
> for (i in patients){print(t.test(i,HC)$p.value)}
[1] 0.005015573
[1] 0.0002672035
[1] 0.00899473

Upvotes: 1

tmpname12345
tmpname12345

Reputation: 2931

Try this: for (i in patients){t.test(get(i),HC)}

The problem is that i is cycling through your patients vector and returning a character. R doesn't know what to do with the character 'P1'. get tells R to look in the environment for an object called 'P1'.

Upvotes: 0

Related Questions