rlinear-regressionposthocancova

Is there a R function to perform an Ancova post-hoc test to check homogeneity of regression slopes


After adjust some linear models I want, first, to test for homogeneity of regression slopes. The second step, and here is my doubt, I want to employ a post-hoc test to compare slopes two by two.

Here goes an example modified from https://www.datanovia.com/en/lessons/ancova-in-r/

get data

data("anxiety", package = "datarium")
anxiety <- anxiety[,c("id","group","t1","t3")]
names(anxiety)[c(3,4)] <- c("pretest","posttest")

plot regression lines

ggscatter(anxiety,x="pretest",y="posttest",color="group",add="reg.line")+
    stat_regline_equation(aes(label=paste(..eq.label.., ..rr.label.., sep = "~~~~"),color = group))

check homogeneity of regression slopes

anova_test(anxiety,posttest~group*pretest)

Here we can see a not statistically significant p-value of 4.15e-01

The post-hoc test emmeans_test perform pairwise comparisons to identify which groups are different. Nevertheless I want to employ a multiple-comparison procedure to determine which B's (slopes) are different from which others.

Is there a function for this? Thanks in advance.


Solution

  • After reading and search more I prepared an example of the analysis I was trying to do. I hope it is useful. An important source was https://cran.r-project.org/web/packages/emmeans/vignettes/interactions.html

    ## packages
    library(ggpubr)
    library(rstatix)
    library(emmeans)
    library(data.table)
    
    ## prepare the example data
    rm(list = ls())
    set.seed(321)
    
    a1 <- 0
    b1 <- 1
    a2 <- 1
    b2 <- 1.7
    
    x <- c(1:10)
    y1 <- (a1+b1*x)+rnorm(10,0,.6)
    y2 <- (a1+b1*x)+rnorm(10,0,.6)
    y3 <- (a2+b1*x)+rnorm(10,0,.6)
    y4 <- (a2+b2*x)+rnorm(10,0,.6)
    
    dat <- data.frame(x=rep(x,4),y=c(y1,y2,y3,y4),group=rep(c("A","B","C","D"),each=10))
    
    ## regression and coefficients
    lm.dat <- lm(y~x*group,dat)
    summary(lm.dat)
    
    ## coeficients, confidence intervals and R2 by group
    as.data.table(dat)[,as.list(coef(lm(y~x))),by=group]
    as.data.table(dat)[,as.list(confint(lm(y~x))),by=group]
    as.data.table(dat)[,list(r2=summary(lm(y~x))$r.squared),by=group]
    
    ## plots
    emmip(lm.dat,group~x,cov.reduce=range)
    ggscatter(dat,x="x",y="y",color="group",add="reg.line")+
        stat_regline_equation(aes(label=paste(..eq.label.., ..rr.label.., sep = "~~~~"),color = group))
    
    ## anova
    anova(lm.dat)
    anova_test(dat,y~x*group)
    
    ## interactions with covariates
    ## slopes for each group and pairwise comparisons
    emtrends(lm.dat,pairwise~group,var="x")