我理解这个问题可以将变量从调用它的 R 脚本推送到 Rnw 文件,方法是将该变量存储在 R 脚本内的全局环境中。我试过这样做,但我无法让 Sweave 文件识别该变量。
例如,如果我有一个 R 脚本(比如说test.R
),如下所示:
TESTGLOBALVARIABLE <<- "XXXXXXXXXTESTGLOBALVARIABLEXXXXXXXXXXX"
system("R CMD Sweave /foo/bar/test.Rnw"))
看起来test.Rnw
像:
\documentclass{article}
\usepackage[absolute]{textpos}
\setlength{\TPHorizModule}{30mm}
\setlength{\TPVertModule}{\TPHorizModule}
\textblockorigin{10mm}{10mm} % start everything near the top-left corner
\setlength{\parindent}{0pt}
\begin{document}
\begin{textblock}{3}(0,0)
The test global variable is: \Sexpr{TESTGLOBALVARIABLE}
\end{textblock}
\begin{textblock}{2}(2,1)
\textblocklabel{block two}
Here is another, slightly narrower, block, at position (2,1) on the page.
\end{textblock}
\end{document}
当我运行 test.R 时,出现错误Error: at test.Rnw:13, object 'TESTGLOBALVARIABLE' not found Execution halted
。
我检查过类似的问题这个。不用 brew 可以做到这一点吗?
答案1
当你获取文件.R 时它会起作用吗?
\documentclass{article}
\usepackage[absolute]{textpos}
\setlength{\TPHorizModule}{30mm}
\setlength{\TPVertModule}{\TPHorizModule}
\textblockorigin{10mm}{10mm} % start everything near the top-left corner
\setlength{\parindent}{0pt}
\begin{document}
<<sourcing_r, include=FALSE, echo=FALSE, results=hide>>=
source(file = "/foo/bar/test.R")
@
\begin{textblock}{3}(0,0)
The test global variable is: \Sexpr{TESTGLOBALVARIABLE}
\end{textblock}
\begin{textblock}{5}(2,1)
\textblocklabel{block two}
Here is another, slightly narrower, block, at position (2,1) on the page.
\end{textblock}
\end{document}
答案2
受到 nebi 答案的启发,我可以通过创建一个单独的 R 脚本来做到这一点,该脚本set_vars2.R
由以下人员编写test.R
:
如果test.R
是:
directory <- "/foo/bar/"
setwd(directory)
file.create(paste0(directory, "set_vars2.R", open = "r"))
fileConn <- file(paste0(directory, "set_vars2.R"))
writeLines(c("TESTGLOBALVARIABLE <<- \"XXXXTESTGLOBALVARIABLEXXXXX\"",""), fileConn)
close(fileConn)
system(paste0("R CMD Sweave ", directory, "test.Rnw"))
system(paste0("pdflatex ", directory, "test.tex"))
并且test.Rnw
是:
\documentclass{article}
\usepackage[absolute]{textpos}
\setlength{\TPHorizModule}{30mm}
\setlength{\TPVertModule}{\TPHorizModule}
\textblockorigin{10mm}{10mm} % start everything near the top-left corner
\setlength{\parindent}{0pt}
\begin{document}
<<sourcing_r, include=FALSE, echo=FALSE, results=hide>>=
source("/foo/bar/set_vars2.R")
@
\begin{textblock}{3}(0,0)
The test global variable is \Sexpr{TESTGLOBALVARIABLE}
\end{textblock}
\end{document}