Search code examples
rformattingplotmath

R: add text to an expression


From sfsmisc package I have an expression and I want to add a text before that. How can I add text on an expression?

library(sfsmisc)
v <- pretty10exp(500)
title <- paste("some text ", v)
plot(1:5, 1:5, main = title)

This plots title as some text 5 %*% 10^2 but not the formatted text.


Solution

  • I think if you use parse it will satisfy the R interpreter. parse returns an unevaluated 'expression'-classed value. You just need to make sure there are tildes (~) where you want spacing:

    v <- pretty10exp(500)
    title <- parse(text= paste("some ~text ~", v ) ) 
    plot(1:5, 1:5, main = title)
    
    title
    #expression(some ~text ~ 5 %*% 10^2)
    

    Expressions in R need to satisfy the parsing rules of the R language, e but the symbols or tokens don't need to refer to anything in particular in the applications since they will only be displayed "as is". So I decided to use parse as the constructor of the expression rather than trying to prepend text onto an existing expression. Between every token, there needs to be a separator. There can also be function-type use of parentheses "(" or square brackets "[", but they will need to be properly paired.

    > expression( this won't work)   # because of the lack of separators
    Error: unexpected symbol in "expression( this won"
    > expression( this ~ won't *work)
    +                           # because it fails to close after the single quote
    > expression( this ~ won\'t *work)
    Error: unexpected input in "expression( this ~ won\"
    > expression( this ~ won\\'t *work)
    Error: unexpected input in "expression( this ~ won\"
    > expression( this ~ will *work)
    expression(this ~ will * work)      # my first successful expression
    > expression( this ~ will *(work)
    + but only if properly closed)     # parsing continued to 2nd line after parens.
    Error: unexpected symbol in:
    "expression( this ~ will *(work)
    but"
    > expression( this ~ will *(work)    # no error so far anyway
    + *but~only~if~properly~closed)
    Error: unexpected '~' in:
    "expression( this ~ will *(work)
    *but~only~if~"
    > expression( this ~ will *(work)
    + *but~only~'if'~properly~closed)
    # At last ... acceptance
    expression(this ~ will * (work) * but ~ only ~ "if" ~ properly ~ 
        closed)
    

    That last one comes about because there are a few (very few) reserved words in R and if happens to be one of them. See ?Reserved