如何评估变量作为 R 中轴标签的表达式?
How to evaluate a variable as an expression for axis label in R?
Objective 允许用户将字符串传递给绘图函数并将其正确计算为 plotmath
.
问题是如何将求值表达式与其他字符串文本结合起来。
似乎任何其他字符串或表达式的存在都会使标签的评估无效。
示例:
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
这是第二个图的输出,显示缺少 label1
:
预期输出:
其他(可能被误导)尝试:
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
类似:Evaluate expression given as a string
只需使用 eval(parse(text=label1))
,就像链接的答案所建议的那样,或者更简单地说,paste("First part", label1)
。
Objective 允许用户将字符串传递给绘图函数并将其正确计算为 plotmath
.
问题是如何将求值表达式与其他字符串文本结合起来。
似乎任何其他字符串或表达式的存在都会使标签的评估无效。
示例:
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
这是第二个图的输出,显示缺少 label1
:
预期输出:
其他(可能被误导)尝试:
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
类似:Evaluate expression given as a string
只需使用 eval(parse(text=label1))
,就像链接的答案所建议的那样,或者更简单地说,paste("First part", label1)
。