TukeyHSD 和 multcompView with dplyr and broom in R

TukeyHSD and multcompView with dplyr and broom in R

broom网站上提到它可以用于TukeyHSDmultcomp(参见here)。但是,我不知道如何将 broom 用于 TukeyHSDmultcomp

参见下面给出的 MWE。

df1 <- data.frame(
  Rep = factor(rep(1:3, each = 4, times = 2)),
  Trt = rep(paste0("T", 1:4), times = 6),
  Loc = rep(paste0("Loc", 1:2), each = 12), 
  Y   = rnorm(24)
)

library(dplyr)
df2 <- filter(df1, Loc=="Loc1")

fm1 <- aov(Y ~ Rep + Trt , data = df2)
anova(fm1)

library(multcompView)

fm1Tukey1 <- 
  data.frame(Letter = multcompLetters(TukeyHSD(fm1)$Trt[, "p adj"])$Letters)
fm1Tukey <- data.frame(Trt = row.names(fm1Tukey1), fm1Tukey1)

fm1Means1 <- 
  data.frame(
      Mean = as.matrix(model.tables(x = fm1, type = "means")[[1]]$Trt)
    , SE   = model.tables(x = fm1, type = "means", se = TRUE)$se$Trt
  )
names(fm1Means1) <- c("Mean", "SE")

fm1Means2 <- data.frame(Trt = row.names(fm1Means1), fm1Means1)
fm1Means <- left_join(fm1Means2, fm1Tukey)


library(dplyr)
fm3 <-
  df1 %>% 
  group_by(Loc) %>% 
  do(model = aov(Y ~ Rep + Trt , data = .))

fm3$model

library(broom)

fm3 %>% tidy(model)

这个解决方案怎么样?

fm3 <-
  df1 %>% 
  group_by(Loc) %>% 
  do(multitst = TukeyHSD(aov(Y ~ Rep + Trt , data = .)))
fm3 %>% tidy(multitst)

结果是:

# A tibble: 18 x 7
# Groups:   Loc [2]
      Loc   term comparison    estimate   conf.low conf.high adj.p.value
   <fctr> <fctr>      <chr>       <dbl>      <dbl>     <dbl>       <dbl>
 1   Loc1    Rep        2-1  1.06654704 -0.5666584 2.6997525   0.1920531
 2   Loc1    Rep        3-1  0.07349636 -1.5597091 1.7067018   0.9895627
 3   Loc1    Rep        3-2 -0.99305068 -2.6262561 0.6401548   0.2283849
 4   Loc1    Trt      T2-T1  0.66688371 -1.4607989 2.7945663   0.7105928
 5   Loc1    Trt      T3-T1 -0.34873829 -2.4764209 1.7789443   0.9382673
 6   Loc1    Trt      T4-T1  0.76089899 -1.3667836 2.8885816   0.6281933
 7   Loc1    Trt      T3-T2 -1.01562201 -3.1433046 1.1120606   0.4201776
 8   Loc1    Trt      T4-T2  0.09401528 -2.0336673 2.2216979   0.9985800
 9   Loc1    Trt      T4-T3  1.10963728 -1.0180453 3.2373199   0.3556331
10   Loc2    Rep        2-1 -0.59970808 -2.4360070 1.2365908   0.6023328
11   Loc2    Rep        3-1 -0.29558179 -2.1318807 1.5407171   0.8768041
12   Loc2    Rep        3-2  0.30412629 -1.5321726 2.1404252   0.8702266
13   Loc2    Trt      T2-T1 -1.06715766 -3.4594233 1.3251080   0.4703902
14   Loc2    Trt      T3-T1 -1.38659230 -3.7788579 1.0056733   0.2828393
15   Loc2    Trt      T4-T1 -1.23727832 -3.6295439 1.1549873   0.3616019
16   Loc2    Trt      T3-T2 -0.31943464 -2.7117003 2.0728310   0.9646736
17   Loc2    Trt      T4-T2 -0.17012066 -2.5623863 2.2221450   0.9942021
18   Loc2    Trt      T4-T3  0.14931398 -2.2429516 2.5415796   0.9960495