Home > Enterprise >  Creating an expression variable with superscripts, subscripts, etc in R
Creating an expression variable with superscripts, subscripts, etc in R

Time:11-24

Here is a sample dataframe:

df <- tibble(variable =c("gdp", "gdp_ppp"),
             value = c(1000, 2000),
             variable_label=c("GDP", "GDP_PPP"))

I would like to make variable_label an expression or text element of some sort because I want to use it as a title for a series of plots that I have generated using a loop. I could manually type the title using text elements but that would require me to generate each plot independently, as far as I know. For example, I want the "PPP" in "GDP_PPP" to be a subscript when it shows up in the title. Is this possible? Thanks!

CodePudding user response:

You can use parse to convert the strings to expressions. Here's an example of doing that in a loop using ggplot, with which your question was tagged

library(tidyverse)

df <- tibble(variable =c("gdp", "gdp_ppp"),
             value = c(1000, 2000),
             variable_label = c("GDP", "GDP[PPP]"))

for(i in seq(nrow(df))) {
  print(ggplot(df[i,], aes(variable, value))   
    geom_col()  
    ggtitle(parse(text = df$variable_label[i])))
}

Created on 2022-11-23 with screenshot

The input shown in the question is not proper latex or plotmath but looks closer to latex and we could translate it to proper latex if it is necessary to use the form shown in the question. This gives the same as above or we could alternately use ggtitle(TeX(ltx)) if we were using ggplot2.

ltx <- sprintf("$%s$", gsub("_(\\w )", "_{\\1}", "GDP_PPP"))
plot(1, main = TeX(ltx))
  • Related