3

I'm wondering how I can actually display a conditional calculation (see below) I'm using to obtain what I call GG in my R codes (see codes below)?

Details:

To be precise, I want to display in my plot that GG = G1 / G2 (displayed IF type = 1) and ELSE GG = (G1 / G2 ) * 2 (displayed IF type == 2).

For example, if G1 = 1, G2 = 2, what I want to be shown depending on "type" is one of the following:

enter image description here

Note: In the picture above, I used "X 2" out of hurry, but I need an actual x-like mathematical sign for the multiplication sign.

Below is my R code:

G1 = 1  ## Can be any other number, comes from a function
G2 = 2  ## Can be any other number, comes from a function
type = 1 ## Can be either 1 or 2

plot(1:10,ty="n",ann=F, bty="n")

text( 6, 6, expression(paste("GG = ", ifelse(type==1, frac(G1, G2), frac(G1, G2)*2 ), " = ", 
           G1/G2, sep = "")), col = "red4", cex = 1.6 )

2 Answers2

3

Using bquote, use .() to add dynamic values into expression:

type = 1
plot(1:10, ty = "n", ann = F, bty = "n")
text(6, 6,
     bquote(paste("GG = ", frac(.(G1), .(G2)),
                  .(ifelse(type == 1, " × 2", "")),
                  " = ", 
                  .(ifelse(type == 1, G1/G2 * 2, G1/G2)), sep = "")),
     col = "red4", cex = 1.6)

enter image description here

Note: ASCII code for Multiplication Sign(×) is Alt 0215

zx8754
  • 52,746
  • 12
  • 114
  • 209
0

Awesome @zx8754, very nice.

I misunderstood your question and thought you wanted to print the formula and result so I produced this.

plot(1:10,ty="n",ann=F, bty="n")
text( 6, 6, if (type==1) substitute(paste("GG = ", frac(G1, G2)) == list(x), list(x=G1/G2)) else
               substitute(paste("GG = ", frac(G1, G2), " x 2") == list(x), list(x=G1/G2 * 2)), col = "red4", cex = 1.6 )

enter image description here

Djork
  • 3,319
  • 1
  • 16
  • 27