Super scripts in Rmarkdown text, R plots, and Rmarkdown tables

Superscripting is easy in MS Word. Its harder in Rmarkdown and R, and unfortunatley requires different code depending on the context. Below I show how to do it within the text of rendered Rmarkdown document, in a plot (works for any R context, whether in Rmarkdown or not), and in a rendered Rmarkdown table using the package pander.



Superscript in Rmarkdown

  • “R^2” prints R^2
  • “R2” prints R2
    • note 2nd carrot after the “2”




Plotting super scripts in R plots

  • This requires using the expression() and paste() commands
  • expression() convert R^2 into R w/ a superscript
  • paste() is used to combine R^2 w/ the value
  • This works in any R context and it not specific to Rmarkdown

Model cat data

library(MASS)
data("cats")

mod <- lm(Hwt ~ Bwt, data = cats)

Do summary of model

mod.sum <- summary(mod)

Get R2 value

library(grDevices)
R2 <- mod.sum$r.squared
R2.exp <- expression(paste(" ",R^2 ,"= 0.647"))

Annotate plot with text()

plot(Hwt ~ Bwt, data = cats)
abline(mod)
text(x = 1.95, y = 18, 
     label = R2.exp,
     pos = 4)

# NOTE: pos = 4 right justifies the symbol

Annotate plot with mtext()

plot(Hwt ~ Bwt, data = cats)
abline(mod)
mtext(R2.exp,
      side = 3,      #side = 3 sets to the top margin
      line = -1.75,  #-1.75 sets below the box
      adj = 0)       #adj=0 left justifies



Super script in Rmarkdown table using pander()

temp.df <- data.frame(c(mod.sum$fstatistic[1],mod.sum$r.squared))

names(temp.df) <- NULL

row.names(temp.df) <- c("F","$R^2$")

library(pander)
## Warning: package 'pander' was built under R version 3.3.2
pander(temp.df)
F 259.8
\(R^2\) 0.6466