1

I created a function to make a ggplot2 graphic. In this function, I am passing a string as a variable that I would like to use as the y-label. To do so, I am using parse(). The following works fine:

library(ggplot2) ylab <- "xxx ~(x^2)" plot_fun <- function(ylab) { ggplot() + ylab(parse(text = ylab)) } plot_fun(ylab) 

In the next example, I have an error because of the % sign.

ylab <- "xxx ~(%)" plot_fun(ylab) #> Error in parse(text = ylab): <text>:1:7: unexpected input #> 1: xxx ~(%) #> ^ 

Is there a better way to parse the string?

Created on 2020-09-17 by the reprex package (v0.3.0.9001)

0

2 Answers 2

2

Put backticks in between the "%" the symbol :

ylab <- "xxx ~(`%`)" plot_fun(ylab) 
Sign up to request clarification or add additional context in comments.

Comments

1

Try this formating your labels with expression() if necessary:

ylab <- expression(xxx ~"(%)") plot_fun(ylab) 

Output:

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.