Search code examples
rpapaja

Formatting table from apa_list(list)


I am printing a table to PDF with much success. Standard hierarchical regression with three steps. However, my questions is twofold: 1) How do I add the asterisk to mark sig p values on the covariates and 2) how do I remove rows like AIC etc. At this point, I am just opening the pdf in word to edit the table but thought someone might have a solution.

H_regression <- apa_print(list(Step1 = model1, 
                               Step2 = model2, 
                               Step3 = model3), 
                          boot_samples = 0)

Solution

  • I'll use the example from the papaja documentation as an example.

    mod1 <- lm(Sepal.Length ~ Sepal.Width, data = iris)
    mod2 <- update(mod1, formula = . ~ . + Petal.Length)
    mod3 <- update(mod2, formula = . ~ . + Petal.Width)
    
    moi <- list(Baseline = mod1, Length = mod2, Both = mod3)
    
    h_reg <- apa_print(moi, boot_samples = 0)
    h_reg_table <- h_reg$table
    

    2) how do I remove rows like AIC

    The table returned by apa_print() is a data.frame with some additional information. Hence, you can index and subset it as you would any other table. You can select rows by name (see below) or by row number.

    # Remove rows
    rows_to_remove <- c("$\\mathrm{AIC}$", "$\\mathrm{BIC}$")
    h_reg_table <- h_reg_table[!rownames(h_reg_table) %in% rows_to_remove, ]
    

    1) How do I add the asterisk to mark sig p values on the covariates

    There is currently no way to highlight significant predictors (I'm not a fan of this practice). But here's some code that will let you add highlighting after the fact. The following function takes the formatted table, the list of the compared models and a character symbol to highlight significant predictors as input.

    # Define custom function
    highlight_sig_predictors <- function(x, models, symbol) {
      n_coefs <- sapply(models, function(y) length(coef(y)))
    
      for(i in seq_along(models)) {
        sig_stars <- rep(FALSE, max(n_coefs))
        sig_stars[1:n_coefs[i]] <- apply(confint(models[[i]]), 1, function(y) all(y > 0) || all(y < 0))
        x[1:max(n_coefs), i] <- paste0(x[1:max(n_coefs), i], ifelse(sig_stars, symbol, paste0("\\phantom{", symbol, "}")))
      }
    
      x
    }
    

    Now this function can be used to customize the table returned by apa_print().

    # Add significance symbols to predictors
    h_reg_table <- highlight_sig_predictors(h_reg_table, moi, symbol = "*")
    
    # Print table
    apa_table(h_reg_table, escape = FALSE, align = c("lrrr"))