Home > Net >  How to reverse the group comparison order for t.test()?
How to reverse the group comparison order for t.test()?

Time:11-12

I would like to conduct a two-sample independent t-test and my grouping variable, "group" is factored as '0' and '1'. When calling the t.test(), it calculates the difference as mean for group 0 - mean for group 1, giving me a negative difference and negative confidence intervals.

How can I reverse the order of comparison so that R estimates mean for group 1 - mean for group 0? I know it compares alphabetically, so I assume it compares numbers in increasing value. I already tried fct_rev() from the forcats package to set group '1' as the reference group, but that did not change the order in which t.test compared and still gave negative outputs. This is important as it is a 1 sided test so I have expectations on the sign of the difference.

Thanks!

EDIT: I'd like to keep the names as '0' and '1' because they need to be coded as such for subsequent analyses to work

CodePudding user response:

You can use the levels argument when constructing the factor. It is possible to revert the levels (see code below) and it is also possible to specify an arbitrary order:

# two samples with different mean
x <- c(rnorm(10, 5, 1), rnorm(10, 8, 1))

# the grouping variable
f1 <- factor(rep(0:1, each=10))

# the grouping variable with reverse order of levels
f2 <- factor(f1, levels=rev(levels(f1)))

t.test(x ~ f1)

t.test(x ~ f2)

CodePudding user response:

For some reason I cannot comment, can you not simply recode your variables and rerun it so they run in the correct order? e.g.:

mydata <- read.csv(yourdataset.csv, na.strings = "")
#make a new "recoded group" variable
mydata$group.recoded <- mydata$group
mydata <- within(mydata, group.recoded[group.variable==group0] <- "group2")

  • Related