使用knitr中的\Sexpr{}公式的未赋值内联代码

使用knitr中的\Sexpr{}公式的未赋值内联代码,r,latex,knitr,R,Latex,Knitr,我喜欢使用\Sexpr{''}作为内联R代码,包括高亮显示。然而,这似乎不适用于公式。似乎瓷砖是个问题。它只是没有显示在pdf中 下面是一个简单的例子: \documentclass{article} \begin{document} <<setup, echo=FALSE>>= library("knitr") knit_hooks$set(inline = function(x) { if (is.numeric(x)) return(knitr:::for

我喜欢使用
\Sexpr{''}
作为内联R代码,包括高亮显示。然而,这似乎不适用于公式。似乎瓷砖是个问题。它只是没有显示在pdf中

下面是一个简单的例子:

\documentclass{article}
\begin{document}

<<setup, echo=FALSE>>=
library("knitr")

knit_hooks$set(inline = function(x) { 
  if (is.numeric(x)) return(knitr:::format_sci(x, 'latex')) 
  highr:::hi_latex(x) 
}) 
@

\Sexpr{'plot(x, y)'} works.

\Sexpr{'lm(response ~ treatment, data)'} does not show the tilde.

\end{document}
\documentclass{article}
\开始{document}
=
图书馆(“knitr”)
knit_hooks$set(内联=函数(x){
if(is.numeric(x))返回(knitr:::format_sci(x,'latex'))
High:::hi_乳胶(x)
}) 
@
\Sexpr{'plot(x,y)}有效。
\Sexpr{'lm(response~treatment,data)}不显示波浪号。
\结束{document}
我得到的是:


非常感谢您的帮助。

请仔细查看您在安装程序中定义的内联函数的结果:

inline('lm(response ~ treatment, data)')

"[1]  \\hlkwd{lm}\\hlstd{(response} \\hlopt{~} \\hlstd{treatment, data)}"
这里有两个问题:tilde标记为\hlopt{},而不是\hlstd{},并且没有正确地标记为LaTeX的符号。为此,您需要将其作为
\textascitilde
插入

我不知道是否有办法修改
high::hi_latex
以正确解释所有数学符号,如波浪形。除此之外,您还可以按如下方式事后修改LaTeX输出:

<<setup, echo=FALSE, message=FALSE>>=
library(knitr)
library(dplyr)
library(stringr)

knit_hooks$set(inline = function(x) { 
  if (is.numeric(x)) return(knitr:::format_sci(x, 'latex')) 
  highr:::hi_latex(x) %>% 
    str_replace("~", "\\\\textasciitilde") %>% 
    str_replace("hlopt", "hlstd")
  }) 
@
=
图书馆(knitr)
图书馆(dplyr)
图书馆(stringr)
knit_hooks$set(内联=函数(x){
if(is.numeric(x))返回(knitr:::format_sci(x,'latex'))
High:::hi_乳胶(x)%>%
str\u replace(“~”,“\\\\textascitilde”)%>%
str_替换(“hlopt”、“hlstd”)
}) 
@

仔细查看您在设置中定义的内联函数的结果:

inline('lm(response ~ treatment, data)')

"[1]  \\hlkwd{lm}\\hlstd{(response} \\hlopt{~} \\hlstd{treatment, data)}"
这里有两个问题:tilde标记为\hlopt{},而不是\hlstd{},并且没有正确地标记为LaTeX的符号。为此,您需要将其作为
\textascitilde
插入

我不知道是否有办法修改
high::hi_latex
以正确解释所有数学符号,如波浪形。除此之外,您还可以按如下方式事后修改LaTeX输出:

<<setup, echo=FALSE, message=FALSE>>=
library(knitr)
library(dplyr)
library(stringr)

knit_hooks$set(inline = function(x) { 
  if (is.numeric(x)) return(knitr:::format_sci(x, 'latex')) 
  highr:::hi_latex(x) %>% 
    str_replace("~", "\\\\textasciitilde") %>% 
    str_replace("hlopt", "hlstd")
  }) 
@
=
图书馆(knitr)
图书馆(dplyr)
图书馆(stringr)
knit_hooks$set(内联=函数(x){
if(is.numeric(x))返回(knitr:::format_sci(x,'latex'))
High:::hi_乳胶(x)%>%
str\u replace(“~”,“\\\\textascitilde”)%>%
str_替换(“hlopt”、“hlstd”)
}) 
@

我最后做的是使用
high:::hi_latex(x)%%>%str\u替换(“hlopt”、“textallt”)
中的textallt定义。这正是我所希望的。你的帮助使我达到了目的。谢谢我最后做的是使用
highr:::hi_latex(x)%%>%str\u替换(“hlopt”、“textallt”)
,使用来自的textallt定义。这正是我所希望的。你的帮助使我达到了目的。谢谢