How do you pass the "formula" part of t_test (from Rstatix package) as a variable in a function?

55 Views Asked by At

I want to pass the x part of the formula argument (x ~ group) in t_test from rstatix as an argument in a separate function but I'm not sure how to format it in the function.

fn_ttest <- function(xvar){df %>% t_test(formula = xvar ~ group)} does not work and results in the error

Error in mutate(): ℹ In argument: data = map(.data$data, .f, ...). Caused by error in map(): ℹ In index: 1. Caused by error in pull(): ! Can't extract columns that don't exist. ✖ Column xvar doesn't exist.

I have also tried:

fn_ttest <- function(xvar){df %>% t_test(formula = .data[[xvar]] ~ group)} which also failed

Sample code:

#dataframe
df <- structure(list(value1 = c(70.0502431525383, 6.59235520497896, 
35.5787350714672, 89.0830702865496, 34.226488200482, 97.126860859571, 
69.1922366039362, 66.3699716343544, 63.877799334703, 47.1427964086179
), value2 = c(67.1878850904759, 48.5704832370393, 57.1540375142358, 
82.6103714043275, 9.8732534640003, 32.9344540028833, 42.5109451573808, 
10.0939717837609, 27.2708899874706, 40.5160438478924), value3 = c(12.4542641534936, 
69.3614622459281, 45.7214235924184, 24.4649752171244, 39.3114057178609, 
27.4378268334549, 47.8188741239719, 28.7748933506664, 46.6750050538685, 
57.547116745729), group = c("A", "A", "A", "A", "A", "B", "B", 
"B", "B", "B")), class = "data.frame", row.names = c(NA, -10L
))



#works 
df %>% 
  t_test(value1 ~ group)

# A tibble: 1 × 8
  .y.    group1 group2    n1    n2 statistic    df     p
* <chr>  <chr>  <chr>  <int> <int>     <dbl> <dbl> <dbl>
1 value1 A      B          5     5     0.884  7.99 0.402


#doesnt work
fn_ttest <- function(xvar){df %>% 
    t_test(xvar ~ group)
}

fn_ttest(value1)

Error in `pull()`:
! Can't extract columns that don't exist.
✖ Column `xvar` doesn't exist.
Run `rlang::last_trace()` to see where the error occurred.

1

There are 1 best solutions below

0
yixu501 On

Figured it out in case anyone is curious:

fn_ttest <- function(xvar) {
  df %>%
    t_test(as.formula(paste(xvar, "~ group")))
}

fn_ttest("value1")

# A tibble: 1 × 8
  .y.    group1 group2    n1    n2 statistic    df     p
* <chr>  <chr>  <chr>  <int> <int>     <dbl> <dbl> <dbl>
1 value1 A      B          5     5     -1.30  6.25 0.239