使用knitr时,通过for循环添加多个预制数字

时间:2013-12-30 15:16:48

标签: r knitr

我有几个预先制作的数字,我想添加到我正在准备编织的乳胶文件中。

使用for循环添加它们的最佳策略是什么?

非常感谢!

1 个答案:

答案 0 :(得分:0)

我的建议是构建一个数据框来支持有关所需LaTeX图形环境的元数据,然后使用mapply和自定义函数来构建所需的输出。这是一个示例.Rnw文件

\documentclass{article}
\usepackage{hyperref,fullpage}
\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    filecolor=magenta,      
    urlcolor=cyan,
  }


\begin{document}
Thanks to \url{https://classroomclipart.com} for the graphics.

For displaying several pre-made figures you could write out the figure
environments yourself.

\begin{figure}[!h]
  \centering
  \caption{Explicit figure environment. \label{fig:00}}
  \includegraphics[width=0.2\linewidth]{figs/man-working-on-a-computer-clipart-318.jpg}
\end{figure}

To create many figure environments, I would suggest building a data.frame with
captions, figure labels, options, and file paths:

<<>>=
myfigs <-
  data.frame(caption = c("Bright Red Fall Foliage", "Chat 9", "Man On Computer"),
             label   = c("brff", "c9", "moc"),
             option  = c("width=0.1\\linewidth", "width=0.2\\linewidth", "width=0.3\\linewidth"),
             path    = c("figs/bright-red-fall-foliage-photo_8304-Edit.jpg",
                         "figs/chat-9-94.jpg",
                         "figs/man-working-on-a-computer-clipart-318.jpg"),
             stringsAsFactors = FALSE)

myfigs
@

Build a function for creating a figure environment:

<<>>=
build_fig_env <- function(caption = "", label = "", option = "", path = "") {
  cat(
  sprintf("\\begin{figure}[!h]\n\\centering\n\\caption{%s \\label{fig:%s}}\n\\includegraphics[%s]{%s}\n\\end{figure}\n\n\n",
          caption, label, option, path)
  )
}
@

Now call the function using mapply.  The mapply call is wrapped in a call to
invisible to suppress the irrelevant output.

<<results = "asis">>=
invisible(
          mapply(build_fig_env,
                 caption  = myfigs$caption,
                 label    = myfigs$label,
                 option   = myfigs$option,
                 path     = myfigs$path,
                 SIMPLIFY = FALSE)
)
@

This is just one solution to your question.  

\end{document}

输出如下:

或者您可以查看pdf here

enter image description here