7

Hi I'm new to R so I apologise if this is a very basic question. I'm trying to add text to a plot at point 11 on the x axis and point 900 on the y axis that will read t0= -4.0280 with the 0 as subscript. Where t0 <- -4.0280 To do this I've tried:

text(11,900,paste("t[0]=",t0),cex=0.8) 
# which gives 
't[0]= -4.0280'

text(11,900,expression(paste("t[0]=",t0)),cex=0.8) 
# which gives 
't[0]=t0'

# the closest I've gotten is:    
text(11,900,expression(paste(t[0]==t0)),cex=0.8)

which will use subscript but return t0 instead of my value of -4.0280.

Could anyone show me where Ive gone wrong?

Cheers.

Ben
  • 41,615
  • 18
  • 132
  • 227
JJS
  • 73
  • 1
  • 1
  • 4

2 Answers2

5

You can replace expression with substitute. There's no need for the paste. The argument list(t0 = t0) tells substitute to replace the string t0 with the value of the object t0:

plot(1,1)

t0 <- 1.3

text(1, 0.8, substitute(t[0]==t0, list(t0 = t0)), cex = 0.8)

enter image description here

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
5

Slightly shorter than substitute is with bquote:

plot(1,1)
t0 <- -4.0280
text(1, 0.8, bquote("t"[0] ~ "=" ~ .(t0)))

of if you'd like to use paste in there:

text(1, 0.8, (bquote("t"[0]~.(paste0('=',t0)))))

enter image description here

This kind of Q has popped up previously:

Using subscript and variable values at the same time in Axis titles in R

Concatenate strings and expressions in a plot's title

Community
  • 1
  • 1
Ben
  • 41,615
  • 18
  • 132
  • 227
  • 1
    Thanks guys, both of those answers worked great. Just to be clear, when should I use 'paste' if this wasn't the correct use? – JJS Mar 21 '13 at 23:45
  • Here is an example of a few uses of `paste ` http://stackoverflow.com/a/15506875/1036500 – Ben Mar 22 '13 at 00:50
  • I've edited my answer to show how you might use `paste` here, but it's not the most efficient way. I generally use `paste` to create character vectors rather than objects that include variables like your example. That said, I sometimes do something like `eval(parse(text=paste0("examp",i))` where the paste result is evaluated, but this is considered bad practice - `library(fortunes);fortune(106)` – Ben Mar 22 '13 at 01:17