0

Good day. I am an R beginner. I have a data set with 2 different groups (group 1 and group 2) and I would like to do paired t-tests on only group 1 or only group 2. I calculated energy at time point 1 and at time point to for members of each group.

This doesn't give me what I need because it's not by group:

t.test(mydata$energytime1,mydata$energytime2, mu=0, alt="two.sided", conf=0.95, paired=T)

Thanks.

Link below is what my data looks like.

Phil
  • 7,287
  • 3
  • 36
  • 66

1 Answers1

1

Here is one option where we use a logical expression on both columns to subset the column and apply the t.test

# // group 1
with(mydata, t.test(energytime1[group == 1], energytime2[group == 1], mu = 0,
     alt = "two.sided", conf = 0.95, paired = TRUE))

# // group 2
with(mydata, t.test(energytime1[group == 2], energytime2[group == 2], mu = 0,
     alt = "two.sided", conf = 0.95, paired = TRUE))

Or we can split by 'group' into a list, loop over the list with lapply and then do the t.test on the subset of data

lapply(split(mydata, mydata$group), function(dat)
     with(dat, t.test(energytime1, energytime2,  
         alt = "two.sided", conf = 0.95, paired = TRUE)))

Or another option is a group by operation

library(dplyr)
mydata %>%
    group_by(group) %>%
    summarise(ttest_results = list(t.test(energytime1, energytime2,
             alt = "two.sided", conf = 0.95, paired = TRUE)))
akrun
  • 874,273
  • 37
  • 540
  • 662