1

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?

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
Kalif Vaughn
  • 353
  • 2
  • 5
  • 10

2 Answers2

2

papaja generates character strings that can be interpreted by RMarkdown as TeX equations (where the dollar signs open the math environment in TeX).

As far as I know, ggplot2 does not comprehend TeX equations. However, you can convert TeX equations to R expressions, e.g. with the latex2exp package, and then use R expressions in your ggplot.

my_tex_expression <- "$R^2 = .146$"

library(ggplot2)
ggplot(npk) + 
  geom_point(aes(x = N, y = yield)) + 
  xlab(latex2exp::TeX(my_tex_expression))

output plot It might also be useful to check this post on stackoverflow: putting mathematical symbols and subscripts mixed with regular letters in R/ggplot2

Marius Barth
  • 596
  • 2
  • 9
2

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+\\$"))
crsh
  • 1,699
  • 16
  • 33