3

This works fine

data = c(1,3,2)
max_y <- max(data)
plot_colors <- c("blue")
plot(data, type="l", col=plot_colors[1], ylim=c(0,max_y), axes=FALSE, xlab=expression(e[3]))
axis(1, at=c(1,2,3),  lab=expression(e[1],e[2],e[3])  )

But I would like to read the labels on the x-axis from a file. I tried the following:

data = c(1,3,2)
names = vector("expression",3)
names[1] = "e[1]"
names[2] = "e[2]"
names[3] = "e[3]"
max_y <- max(data)
plot_colors <- c("blue")
plot(data, type="l", col=plot_colors[1], ylim=c(0,max_y), axes=FALSE, xlab=expression(e[3]))
axis(1, at=c(1,2,3),  lab=names  )

I tried substitute:

axis(1, at=c(1,2,3),  lab=substitute(expression(a), list(a="e[1],e[2],e[3]"))  )

but this also did not work. Any suggestion?

dziadgba
  • 135
  • 7

2 Answers2

2

What you want is ?parse:

names = c('e[1]', 'e[2]', 'e[3]')
namesExp = do.call(c, lapply(names, function(x) parse(text = x)))
plot(c(1,3,2), type='l', col='blue', axes=FALSE, xlab = expression(e[3]))
axis(3, at=c(1,2,3), lab = names)
axis(1, at=c(1,2,3), lab = namesExp)

Above, lapply returns a list of expressions:

> print(lapply(names, function(x) parse(text = x)))
[[1]]
expression(e[1])
[[2]]
expression(e[2])
[[3]]
expression(e[3])

The do.call just non-recusrively unlists it (also can use unlist(lapply(names, function(x) parse(text = x)), recursive = F)):

> print(do.call(c, lapply(names, function(x) parse(text = x))))
expression(e[1], e[2], e[3])
lockedoff
  • 513
  • 4
  • 10
0

This is ugly as sin but it does what you want. There may be a better way.

data = c(1,3,2)
max_y <- max(data)
plot_colors <- c("blue")
plot(data, type="l", col=plot_colors[1], ylim=c(0,max_y),
     axes=FALSE, xlab=expression(e[3]))

labels <- "e[1],e[2],e[3]"
axis(1, at=c(1,2,3), lab=eval(parse(text=paste("expression(", labels, ")"))))

Let's unpack that a bit:

> paste("expression(", labels, ")")
[1] "expression( e[1],e[2],e[3] )"

> parse(text=paste("expression(", labels, ")"))
expression(expression( e[1],e[2],e[3] ))

> eval(parse(text=paste("expression(", labels, ")")))
expression(e[1], e[2], e[3])

No, you can't just parse labels, because:

> parse(text=labels)
Error in parse(text = labels) : <text>:1:5: unexpected ','
1: e[1],
       ^

And eval seems to be the only way to peel off the outer expression correctly. This alternative appears to work:

> parse(text=paste("expression(", labels, ")"))[[1]]
expression(e[1], e[2], e[3])

But passing that to axis will get you an inexplicable error message about the lengths not matching up. I got nothin'.

zwol
  • 135,547
  • 38
  • 252
  • 361
  • Ah, you beat me to an answer. `parse(text = 'e[1]')` works, so inputting a character vector more or less does the trick (`parse(text = c('e[1]', 'e[2]'))`) – lockedoff Jul 11 '12 at 19:09
  • Actually ignore my comment, but see my answer ;) Yours looks fine too. – lockedoff Jul 11 '12 at 19:16