R: paired t-test on multiple columns

Viewed 45

I am trying to run a t-test on multiple columns. Basically trying to find the change from baseline to year 1 for a number of joint angles. I only want to conduct this on the study side. Below is an image with the first few rows and columns of the data. Sample Data

I have tried using both of these functions without success:

Code 1:

res <- FAI_SLS %>% 
  filter(study_side == "Study")%>%
  select(-id,-subject,-activity,-side,-study_side,-year) %>%
  map_df(~ broom::tidy(t.test(. ~ year)), .id = 'var')

I get the following error:

Error in eval(predvars, data, env) : object 'year' not found

I tried taking out -year but I still have the same issue.

Code 2:

t(sapply(FAI_SLS%>%filter(study_side == "Study")%>%select(-id,-subject,-activity,-side,-study_side,-year), function(x) 
     unlist(t.test(x~FAI_SLS$year)[c("estimate","p.value","statistic","conf.int")])))

I get the following error:

Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 't': variable lengths differ (found for 'FAI_SLS$year')

Again I tried taking -year out without success.

Any suggestions on how I can fix this? Thanks

1 Answers

Try fitting the t-test within summarise() on all the columns you want to test (selected in across()). Here's an example with a different dataset:

library(dplyr)
library(tidyr)
data("storms")

storms %>% 
  filter(year %in% c(2019, 2020)) %>% 
  summarise(across(-c(name, year, status, category), 
                ~broom::tidy(t.test(. ~ year)))) %>% 
  pivot_longer(everything(), names_to = "variable") %>% 
  unnest(value)

#> # A tibble: 9 × 11
#>   variable    estimate estimate1 estimate2 statistic  p.value parameter conf.low
#>   <chr>          <dbl>     <dbl>     <dbl>     <dbl>    <dbl>     <dbl>    <dbl>
#> 1 month         0.0917      8.93      8.84     1.15  2.52e- 1      892.  -0.0654
#> 2 day           4.29       18.2      13.9      7.49  2.34e-13      641.   3.17  
#> 3 hour         -0.0596      9.13      9.19    -0.128 8.99e- 1      687.  -0.978 
#> 4 lat           2.14       25.9      23.7      3.75  1.94e- 4      668.   1.02  
#> 5 long          6.06      -60.7     -66.8      4.27  2.25e- 5      736.   3.27  
#> 6 wind          8.42       58.8      50.4      4.42  1.18e- 5      529.   4.68  
#> 7 pressure     -4.46      989.      993.      -3.03  2.59e- 3      537.  -7.35  
#> 8 tropicalst…   7.39      153.      145.       0.810 4.18e- 1      701. -10.5   
#> 9 hurricane_…  10.9        24.1      13.2      3.92  1.02e- 4      508.   5.45  
#> # … with 3 more variables: conf.high <dbl>, method <chr>, alternative <chr>

Created on 2022-06-02 by the reprex package (v2.0.1)

Related