rtukey

Referencing object elements


I'm trying to access individual elements of an object returned from TukeyHSD function. I can see how to access the individual elements, but how do I access the labels?

$`Auto$CargoSpace`
                  diff       lwr        upr        p adj
wagon-SUV -3747.333 -7664.507  -980.0801 6.855348e-03
trunk-SUV  -4792.333 -5621.311 -2371.3357 2.065806e-05
trunk-wagon  -968.000 -3823.523  2125.54328 7.410039e-01

I'd like to be able to access each row/column combination the way I can with a tibble or dataframe. That way I can add an interpretation later in the code. Let's say I wanted to end up with this result:

CargoSpace p adj Analysis

wagon-SUV 6.85 Unlikely to produce a benefit

trunk-SUV 2.06 Worth investigating


Solution

  • We extract the output with $, then use either grep (if partial matches) or %in% (for fixed matching) to subset the rows, create a data.frame with the row names of the subset of the dataset along with "p adj" column. Then, we can create 'Analysis' column based on the value of 'p.adj'

    out1 <- out$`Auto$CargoSpace`
    out2 <- out1[grep("SUV$", row.names(out1),]
    out3 <- data.frame(CargoSpace = row.names(out2), p.adj = out2[, "p adj"])
    out3$Analysis <- ifelse(out2$p.adj < 0.0001, "Worth investigating", "Unlikely to produce a benefit")
    

    Reproducible example

    fm1 <- aov(breaks ~ wool + tension, data = warpbreaks)
    out <- TukeyHSD(fm1, "tension", ordered = TRUE)
    
    
    
    out$tension
    #         diff        lwr      upr       p adj
    #M-H  4.722222 -4.6311985 14.07564 0.447421021
    #L-H 14.722222  5.3688015 24.07564 0.001121788
    #L-M 10.000000  0.6465793 19.35342 0.033626219