21

i want to achieve an title in R plot as the following:

title = "The significance level you entered is alpha = 0.05 which is often used."

In order to get this I split the whole text in little parts, so i finally can write

title = paste(part1,part2,part3,part4)

The parts are:

part1 = "The significance level you entered is"

part2 = expression(alpha)

part3 = object@attribute

part4 = " which is often used."

So I'm not able to combine these parts to get my result.

Either the symbol is shown correctly and the part 3 is printed as object@attribute (ant not his value) or the symbol is not shown and the value of the object is printed correctly.

I used ?expressionand ?printalready, but didn't get it

The examples provided in ?plotmath didn't match my case either.

mido
  • 22,784
  • 14
  • 89
  • 113
user3093283
  • 323
  • 1
  • 2
  • 5
  • 2
    Hi before I started this topic I had a look at this thread. But the difference here ist, that i want concatenate symbols, text and value of a variable. The concatenation ist not that problem, but the evaluating of my object attribute. It is always printed out as object@attribute instead of 0.05. – user3093283 Dec 11 '13 at 23:42
  • 3
    1. In my opinion, this is a clearly stated legitimate question. 2. In general, the system of plotmath/expression/bquote usage in R is quite difficult even for experienced users. No single existing SO question on the topic is definitive. 3. Four of the five users who voted to close have zero [r] questions or answers. – bdemarest Dec 13 '13 at 08:54
  • Wow, this was inappropriately marked as a duplicate! The so called duplicate is basically irrelevant to this question. This question is about adding a variable's value to a title not just an 'expression'. – WetlabStudent Jul 03 '15 at 02:09

1 Answers1

28

One solution is to use bquote(). Use .() within bquote to get the value of objects or expressions. Here is one example of how that might work:

obj = list(foo=0, bar=99, alpha=0.05)
plot(1:10, main=bquote("Significance level is" ~ alpha == .(obj$alpha)))

The tilde ~ seems necessary here to convince bquote to treat alpha as a plotmath expression.

enter image description here

bdemarest
  • 13,979
  • 3
  • 48
  • 54
  • Works well, thanks for your time!! – user3093283 Dec 12 '13 at 01:40
  • 1
    If you want to use this for a `geom_label` in `ggplot2`, you have to wrap this in `as.expression`: `as.expression(bquote("Significance level is" ~ alpha == .(mean(x))))`. – MS Berends Nov 06 '18 at 20:26
  • In my case, I need to start the line with `^1` - superscript number, which bquote seems to dislike. Would be interested in any suggestions (`expression(""^1") is not a solution, since I want to put the content of `text_in_var` and it seems the latter is not easy to do with `expression` – JelenaČuklina Nov 10 '20 at 10:16
  • @JelenaČuklina, try something like this: ```x – bdemarest Nov 12 '20 at 18:28