Generate a list of expression literals from an integer sequence
Asked Answered
H

2

4

I would like to map a sequence of integers to a sequence of expression literals in order to use the latter as tick mark labels in a plot, e.g.

lbls <- lapply(-2:2, function(i) expression(i * pi))
plot(...)
axis(1, at=seq(-2,2)*pi, labels=lbls)

So far I've tried all variations of bquote, substitute, expression etc. that I could think of, but apparently I must have missed something. Also, the FAQ and related SO questions & answers didn't fully solve this for me.

How would I do it correctly (I want axis to render pi as the greek letter and have -2 ... 2 substituted for i in the above example)?

Hitandmiss answered 6/4, 2012 at 10:27 Comment(0)
N
4

try this:

lbls <- do.call("expression", lapply(-2:2, function(i) substitute(X * pi, list(X = i))))
plot(-10:10, -10:10, xaxt="n")
axis(1, at=seq(-2,2)*pi, labels=lbls)

enter image description here

Nichols answered 6/4, 2012 at 10:33 Comment(1)
Thanks @Roman or, using bquote you can write like this: lbls <- do.call("expression", lapply(-2:2, function(i) bquote(.(i) * pi)))Nichols
M
2

Try this:

lbls <- parse(text = paste(seq(-2, 2), "pi", sep = "*"))
Macario answered 6/4, 2012 at 10:48 Comment(2)
Nice one! I must have overlooked the text parameter in ?parse.Hitandmiss
This suggestion is more helpful for those whose expressions are quite different in the list. Thanks!Bandy

© 2022 - 2024 — McMap. All rights reserved.