cNi*_*nja 6 formatting r plotmath
从sfsmisc包中我有一个表达式,我想在此之前添加一个文本.如何在表达式上添加文本?
library(sfsmisc)
v <- pretty10exp(500)
title <- paste("some text ", v)
plot(1:5, 1:5, main = title)
Run Code Online (Sandbox Code Playgroud)
这将标题绘制为some text 5 %*% 10^2但不是格式化文本.
我想如果你使用parse它将满足R解释器.parse返回未评估的"表达式"分类值.你只需要确保~你想要间距的tildes():
v <- pretty10exp(500)
title <- parse(text= paste("some ~text ~", v ) )
plot(1:5, 1:5, main = title)
title
#expression(some ~text ~ 5 %*% 10^2)
Run Code Online (Sandbox Code Playgroud)
R中的表达式需要满足R语言的解析规则,但是符号或标记不需要在应用程序中特别引用任何内容,因为它们将仅"按原样"显示.所以我决定使用parse表达式的构造函数,而不是尝试将文本添加到现有表达式.在每个令牌之间,需要有一个分隔符.也可以使用括号" ("或方括号" ["的函数类型,但它们需要正确配对.
> 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)
Run Code Online (Sandbox Code Playgroud)
最后一个是因为R中有一些(很少)保留字而if恰好是其中之一.看到?Reserved