0

I need to apply a tukey post hoc test to a dataset with 80 columns/variables based on 3 groups/treatments. Is there any way to get a table with all variables in which common characters identify levels or groups that are not significantly different (based on p-values) in an automated way with a loop function?

1 Answers1

0

Does this work for you?

# packages and function conflicts
library(conflicted)
library(emmeans)
library(multcomp)
library(multcompView)
library(tidyverse)

conflict_prefer("select", winner = "dplyr")
#> [conflicted] Will prefer dplyr::select over any other package


# Create example data
dat <- PlantGrowth %>%
  transmute(
    group = group,
    y1 = weight,
    y2 = weight * runif(30, 0.8, 1.2),
    y3 = weight * runif(30, 0.8, 1.2)
  ) %>%
  as_tibble()

dat
#> # A tibble: 30 x 4
#>    group    y1    y2    y3
#>    <fct> <dbl> <dbl> <dbl>
#>  1 ctrl   4.17  4.22  3.53
#>  2 ctrl   5.58  6.19  6.46
#>  3 ctrl   5.18  5.95  5.66
#>  4 ctrl   6.11  5.36  7.19
#>  5 ctrl   4.5   4.41  5.11
#>  6 ctrl   4.61  3.93  4.89
#>  7 ctrl   5.17  4.36  4.67
#>  8 ctrl   4.53  4.53  4.72
#>  9 ctrl   5.33  4.64  5.86
#> 10 ctrl   5.14  5.34  4.89
#> # ... with 20 more rows

# Loop setup
var_names <- names(dat)[-1]
loop_out <- list()

# Loop
for (var_i in var_names) {
  dat_i <- dat %>%
    rename(y_i = !!var_i) %>%
    select(group, y_i)
  
  mod_i <- lm(y_i ~ group, data = dat_i)
  
  emm_i <- emmeans(mod_i, "group") %>%
    cld(Letters = letters)
  
  loop_out[[var_i]] <- emm_i %>%
    as_tibble() %>%
    select(group, emmean, .group) %>%
    rename_with(.cols = -group,
                .fn = ~ paste(., var_i, sep = "_"))
}

# Join loop results
loop_out %>% reduce(full_join, by='group')
#> # A tibble: 3 x 7
#>   group emmean_y1 .group_y1 emmean_y2 .group_y2 emmean_y3 .group_y3
#>   <fct>     <dbl> <chr>         <dbl> <chr>         <dbl> <chr>    
#> 1 trt1       4.66 " a "          4.46 " a "          4.64 " a"     
#> 2 ctrl       5.03 " ab"          4.89 " ab"          5.30 " a"     
#> 3 trt2       5.53 "  b"          5.74 "  b"          5.39 " a"

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

Check out my summary on the compact letter display for more background.

Paul Schmidt
  • 1,072
  • 10
  • 23