How to evaluate a variable as an expression for axis label in R?

萝らか妹 提交于 2019-12-13 01:11:48

问题


Objective is to allow user to pass a string to a plotting function and have it evaluated correctly as plotmath.

Question is how to combine an evaluated expression with other string text.

It seems the presence of any other string or expression nullifies the evaluation of the label.

Example:

label1 <- 'degree~C'

plot(1:10, type='l', xlab=bquote(.(parse(text=label1))))  #evaluated correctly
plot(1:10, type='l', xlab=bquote('Some text'~~Omega^2~~.(parse(text=label1))))  #missing degree C

Here is the output of the second plot showing that label1 is missing:

Expected output:

Other (possibly misguided) attempts:

plot(1:10, type='l', xlab=substitute(paste('Some text'~~Omega^2~~mystring), list(mystring=label1))) #string not evaluated
plot(1:10, type='l', xlab=substitute(paste('Some text'~~Omega^2~~mystring), list(mystring=parse(text=label1)))) #string missing entirely
plot(1:10, type='l', xlab=substitute(paste('Some text'~~Omega^2~~mystring), list(mystring=expression(text=label1)))) #string missing entirely

Similar: Evaluate expression given as a string


回答1:


Just use eval(parse(text=label1)), like the linked answer suggests, or more simply, paste("First part", label1).



来源:https://stackoverflow.com/questions/35804590/how-to-evaluate-a-variable-as-an-expression-for-axis-label-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!