在replace()表达式中添加换行符 [英] Adding a newline in a substitute() expression

查看:513
本文介绍了在replace()表达式中添加换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用来自回归模型的相关数据来注释ggplot中的图. 我在这篇SO帖子中遵循了上的建议并尝试修改该功能,以在绘图中的换行符中添加几个附加项目. 这是我尝试的新功能:

I'm trying to annotate a plot in ggplot with relevant data from a regression model. I've followed the suggestions in this SO post and tried to modify the function to have a couple additional items in a newline in the plot. This is my attempt at a new function:

lm_eqn = function(m){
  eq <- substitute(italic(y) == a %.% italic(x)^b*","~~italic(r)^2~"="~r2*","~~italic(n)~"="~nn*","~~italic(p-value)~"="~pv, 
                   list(a = format(exp(coef(m)[1]), digits = 3), 
                        b = format(coef(m)[2], digits = 3), 
                        r2 = format(summary(m)$r.squared, digits = 3),
                        nn=format(summary(m)$df[2]),
                        pv=format(summary(m)$coefficients[,4][2])))
  as.character(as.expression(eq));                 
}

它产生预期的输出:全部在一行中.但是我想将文本分为两行,第二行以italic(n)=开头.但是,如果我引入了\n,则在找到\n时会引发错误.如果在引号"\n"中引入\ n,则它似乎被忽略了,并且文本仍保留在一行中.我还没有找到有关如何在这样的表达式中引入换行符的参考.您的帮助将不胜感激.

It produces the expected output: all in one line. But I'd like to split the text in two lines, the second one starting with italic(n)=. But if I introduce a \n, it throws an error when it finds \n. If I introduce the \n inside the quotes: "\n" then it seems to be ignored and the text remains in one line. I haven't found any reference as to how to introduce a newline in such an expression. Your kind help will be much appreciated.

谢谢.

通过@Tim进行评论,我提供了一个重写的代码和已调整的问题.

following a coment by @Tim I present a rewriten code and adjusted question.

推荐答案

\n不能在plotmath表达式中使用.您也许可以将表达式分为两部分,然后使用annotate将表达式添加到所需的位置.或者,使用atop.看看这个帖子-> expression()中的换行符?

\n cannot be used in plotmath expressions. You could perhaps break the expression in two parts, and use annotate to add the expressions where you want them. Or, use atop. Check out this post -> Line break in expression()?

这篇关于在replace()表达式中添加换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆