Search code examples
rggplot2markdownpapaja

apa_print() equations in papaja versus ggplot2 (title)


I am using the papaja package in R markdown (which I love). If I do something like this:

The test regression equation was: `r testregressionx1$full_result$modelfit$r2`

I will get something like this once I knit to pdf (formatted correctly):

R 2 = .10, 90% CI [0.00, 0.45], F(1,10) = 1.07, 239, p = .326

However, if I try to add that information into a ggplot2 figure title like this:

+ggtitle(testregressionx1$full_result$modelfit$r2)

I get something like this (which is bad):

R^2 = .10$, 90\% CI $[0.00$, $0.45]$, $F(1, 1 ...

How can I get the same printout in the figure as I do in the text? Also, how can I reference only the r2 and p-value in the figure?


Solution

  • Since you don't provide a reproducible example I'll work with an example from the documentation.

    library("papaja")
    
    ctl <- c(4.17, 5.58, 5.18, 6.11, 4.50, 4.61, 5.17, 4.53, 5.33, 5.14)
    trt <- c(4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69)
    group <- gl(2, 10, 20, labels = c("Ctl", "Trt"))
    weight <- c(ctl, trt)
    lm_fit <- lm(weight ~ group)
    
    lm_res <- apa_print(lm_fit)
    

    As pointed out by Marius you can use latex2exp::TeX() to convert the LaTeX math into an R expression. The problem here is that this conversion is not flawless with this string, so it requires some additional formatting:

    # Escape brackets and remove backslash in front of percent sign
    modified_r2 <- gsub("\\]", "\\\\]", 
                   gsub("\\[", "\\\\[",
                   gsub("\\\\", "", lm_res$full_result$modelfit$r2)))
    
    ggplot(data.frame(weight, group), aes(x = group, y = weight)) +
      geom_point() +
      ggtitle(TeX(modified_r2))
    

    enter image description here

    If you you only want R^2 and the p-value you similarly need to modify the character string. For example,

    library("stringr")
    
    modified_r2 <- paste0(
      str_extract(lm_res$estimate$modelfit$r2, "\\$R\\^2 = \\.\\d\\d\\$"),
      ", ", 
      str_extract(lm_res$statistic$modelfit$r2, "\\$p = \\.\\d+\\$"))