1

I am trying to perform a series of T-tests using RStatix's t_test(), where the dependent variable is the same in every test and the grouping variable changes. I am doing these tests inside a loop, so I would like to select the grouping variable with the column number instead of the column name. I have tried to do this with colnames(dataframe)[[columnnumber]], but I get the following error: "Can't extract columns that don't exist". How can I select the grouping variable with the column number instead of the column name?

Below is a minimal reproductible example with a ficticious dataframe; the test works correctly when the grouping variable's name (gender) is indicated, but not when the column number is indicated instead.

library(tidyverse)
library(rstatix)
dat<-data.frame(gender=rep(c("Male", "Female"), 1000),
              age=rep(c("Young","Young", "Old", "Old"),500),
              tot= round(runif(2000, min=0, max=1),0))

dat %>% t_test(tot ~ gender,detailed=T) ##Works

dat %>% t_test(tot ~ colnames(dat)[[1]],detailed=T) ##Doesn't work

cholo.trem
  • 314
  • 2
  • 9

2 Answers2

1

colnames(dat)[1] is a string. t_test requires formula object, you need to convert string to formula and pass it in t_test. This can be done using reformulate or as.formula.

library(rstatix)
dat %>% t_test(reformulate(colnames(dat)[1], 'tot'),detailed=T)

# A tibble: 1 x 15
#  estimate estimate1 estimate2 .y.   group1 group2    n1    n2 statistic
#*    <dbl>     <dbl>     <dbl> <chr> <chr>  <chr>  <int> <int>     <dbl>
#1    0.011     0.505     0.494 tot   Female Male    1000  1000     0.492
# … with 6 more variables: p <dbl>, df <dbl>, conf.low <dbl>,
#   conf.high <dbl>, method <chr>, alternative <chr>
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

If we want to use tidyverse way of construction, then do this with in an expr

library(rstatix)
dat %>%
     t_test(formula = eval(rlang::expr(tot ~ !! rlang::sym(names(.)[1]))),
                detailed = TRUE)
# A tibble: 1 x 15
#  estimate estimate1 estimate2 .y.   group1 group2    n1    n2 statistic     p    df conf.low conf.high method alternative
#*    <dbl>     <dbl>     <dbl> <chr> <chr>  <chr>  <int> <int>     <dbl> <dbl> <dbl>    <dbl>     <dbl> <chr>  <chr>      
#1    -0.02     0.497     0.517 tot   Female Male    1000  1000    -0.894 0.371 1998.  -0.0639    0.0239 T-test two.sided

NOTE: values are different as the data was constructed without any set.seed (wrt rnorm)

akrun
  • 874,273
  • 37
  • 540
  • 662