将 R 代码合并到 latex 段落中

将 R 代码合并到 latex 段落中

我有一个大型 R 脚本,我正在尝试将其放入 LaTex 文档中,然后在 LaTex 段落中的文本中引用源代码中创建的特定数据框的输出。

当我编译 PDF 时,我收到一条错误消息,提示未找到对象 num_stations。

一个小例子:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\begin{document}
You can type R commands in your \LaTeX{} document and they will be properly run and the output printed in the document.

<<>>=
opts_chunk$set(echo=F,message=F, warnings=F)

#need com_dredge, table 2.1 and num_stations from this source code
source(file="S:/Adv/Scallop Central/2018 Scallop RSA/Industry Report/Industry Report.R")

#num_stations dataframe needed for text below
num_stations
@
This is a value $\Sexpr{num_stations$Number}$.

\end{document}

当我运行代码块时,我认为源代码行不起作用。我读过几个不同的选项:1. 源文件需要与 knitr 文件位于同一文件夹中。我试过这个,但收到错误消息无法打开连接。2. 在源代码中输入路径。
我也试过那个,得到了同样的消息。3. 使用

  opts_knit$set(root.dir = '/Users/username/path_to_project').

我也在乳胶文件中的代码块中尝试了这个,并得到了相同的消息。

我将不胜感激任何帮助。

答案1

foo.R(在工作目录中):

# ---- test  ----

bah <- data.frame(a=c(1,2,3),b=c(4,5,6))

test.Rnw(在同一工作目录中):

\documentclass{article}
\usepackage{booktabs}
\begin{document}
<<mychuck, cache=F,echo=F>>=
read_chunk('foo.R')
@
<<test,echo=F>>=
@
<<mydata,result="asis",echo=F>>=
kable(bah, caption="my data", booktabs = TRUE)
@
The variable \verb|bah$a| is \Sexpr{combine_words(bah$a)}.
\end{document}

要编译上述文件,请使用 Rstudio 或参阅 如何从命令行构建 Knitr 文档

姆韦

相关内容