Search code examples
rplotgriditalicgmisc

`Gmisc` package: how to add italic to only part of text using the `glue` package?


Using the Gmisc package, how can I add italic to only part of text using the glue package? See the reprex below for details:

library(Gmisc, quietly = TRUE)
library(grid)

grid.newpage()
txt <- "Just a plain box"
boxGrob(txt)


grid.newpage()
txt <- expression(italic("Just a plain box"))
boxGrob(txt)


grid.newpage()
txt <- paste("Just a", expression(italic("plain")), "box")
boxGrob(txt)

Created on 2023-07-12 with reprex v2.0.2

So it seems the italic works only if used on the entire string and not when used inside paste as suggested on the package website here: https://cran.r-project.org/web/packages/Gmisc/vignettes/Grid-based_flowcharts.html

We can alternatively use bquote (as also suggested): this seems to work.

library(Gmisc, quietly = TRUE)
library(grid)

grid.newpage()
txt <- bquote(paste("Just a ", italic("plain"), " box"))
boxGrob(txt)

Created on 2023-07-12 with reprex v2.0.2

However, it seems incompatible with the glue package:

library(Gmisc, quietly = TRUE)
library(grid)
library(glue)

grid.newpage()
txt <- bquote(italic("plain"))
txt
#> italic("plain")
# txt actually has length 2, not 1, so leads to an error
length(txt)
#> [1] 2
expr <- glue("Just a {p} box", p = txt)
expr
#> Just a italic box
#> Just a plain box
boxGrob(expr, p = txt)
#> Error in boxGrob(expr, p = txt): unused argument (p = txt)

Created on 2023-07-12 with reprex v2.0.2

Am I doing something wrong?


Solution

  • One option would be use parse like so:

    library(Gmisc, quietly = TRUE)
    library(grid)
    library(glue)
    
    grid.newpage()
    txt <- 'italic("plain")'
    expr <- glue("Just~a~{p}~box", p = txt)
    boxGrob(parse(text = expr))