从sfsmisc
包中我有一个表达式,我想在此之前添加一个文本。如何在表达式上添加文本?
library(sfsmisc)
v <- pretty10exp(500)
title <- paste("some text ", v)
plot(1:5, 1:5, main = title)
此标题为some text 5 %*% 10^2
,但不是格式化文本。
答案 0 :(得分:5)
我认为如果你使用parse
它将满足R解释器。 parse
会返回未评估的&#39;表达式&-39; -classed值。您只需要确保在需要间距的位置(~
):
v <- pretty10exp(500)
title <- parse(text= paste("some ~text ~", v ) )
plot(1:5, 1:5, main = title)
title
#expression(some ~text ~ 5 %*% 10^2)
R中的表达式需要满足R语言的解析规则,但符号或标记不需要在应用程序中特别引用任何内容,因为它们只会被显示在&#34; #34 ;.所以我决定使用parse
作为表达式的构造函数,而不是尝试将文本添加到现有表达式中。在每个令牌之间,需要有一个分隔符。也可以使用括号的功能类型&#34; (
&#34;或方括号&#34; [
&#34;,但它们需要正确配对。
> expression( this won't work) # because of the lack of separators
Error: unexpected symbol in "expression( this won"
> expression( this ~ won't *work)
+ # because it fails to close after the single quote
> expression( this ~ won\'t *work)
Error: unexpected input in "expression( this ~ won\"
> expression( this ~ won\\'t *work)
Error: unexpected input in "expression( this ~ won\"
> expression( this ~ will *work)
expression(this ~ will * work) # my first successful expression
> expression( this ~ will *(work)
+ but only if properly closed) # parsing continued to 2nd line after parens.
Error: unexpected symbol in:
"expression( this ~ will *(work)
but"
> expression( this ~ will *(work) # no error so far anyway
+ *but~only~if~properly~closed)
Error: unexpected '~' in:
"expression( this ~ will *(work)
*but~only~if~"
> expression( this ~ will *(work)
+ *but~only~'if'~properly~closed)
# At last ... acceptance
expression(this ~ will * (work) * but ~ only ~ "if" ~ properly ~
closed)
最后一个出现是因为R中有少数(极少数)保留字,if
恰好是其中之一。见?Reserved
答案 1 :(得分:0)