【问题标题】:knitr: Is there any way for forloop conditions to include Sexpr?knitr:有没有办法让 forloop 条件包含 Sexpr?
【发布时间】:2013-02-04 05:13:48
【问题描述】:

我正在使用 R 中的 knitr 包来尝试将数据框转换为报告。 问题是输入数据有很多可变性。目的是打印一行文本(从数据框中提取,然后是图表,也来自数据框)

以下代码是相同的精简版本。它不输出PDF文件。

\documentclass{report}
\usepackage{forloop}
\newcounter{tmp}

\begin{document}
\newcommand{\Brep}{$\Sexpr{A}$}

\forloop{tmp}{1}{\value{tmp} < \Brep} {\Brep}

\end{document}

在检查日志和删除部分时,我已将其范围缩小到 knitr/latex 无法评估 forloop 条件下的 \FBrep 部分。

有没有办法解决这个问题? 另外,在下一步中,我需要以类似的方式使用 includegraphics,如下

\includegraphics{\Brep.PNG}

抱歉,这是 RTFM 材料。我真的很新,我确实环顾四周。 谢谢

【问题讨论】:

    标签: r latex knitr


    【解决方案1】:

    你不能让 LaTeX 调用 knitrRknitr 所做的是解析您的文档以获取 R 代码,并评估代码。然后一切都在 R 端完成,你得到一个与 R 无关的静态 LaTeX 输出文档。所以如果你想编写任何东西,就用 R 代码来做

    将您的程序直接翻译成 R:

    \documentclass{report}
    \begin{document}
    
    <<results='asis', echo=FALSE>>=
    for (tmp in 1:A) {
      cat(tmp)
    }
    @
    
    <<results='asis', echo=FALSE>>=
    for (tmp in 1:A) {
      cat(sprintf('\\includegraphics{%d.PNG}', tmp))
    }
    @
    \end{document}
    

    但可以简化为:

    \documentclass{report}
    \begin{document}
    \Sexpr{paste(1:A, collapse = '')}
    \Sexpr{paste(sprintf('\\includegraphics{%d.PNG}', 1:A), collapse = '')}
    \end{document}
    

    我还需要提醒您,这可能不是在文档中插入绘图的理想方法(通常您不需要注意\includegraphics{})。您需要了解这样的自动化:

    \documentclass{report}
    \begin{document}
    <<>>=
    for (i in 1:5) {
      hist(mtcars[, i])
    }
    @
    \end{document}
    

    【讨论】:

    • 感谢您的输入,更不用说包了。问题是,我不确定 R 是否可以将所需的对象格式化到我们需要的程度。
    • @user1808346 然后详细说明所需的格式,看看 R 是否可以提供帮助:)
    • @user1808346 也许你在问github.com/yihui/knitr-examples中的示例075之类的东西
    猜你喜欢
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多