我有五個圖像存儲如下(其中「currentDirectory所」是結果我從命令getwd得到()):我想寫插入多張圖片中的for循環到Sweave文檔
currentDirectory/results/thePlot_1.jpg
currentDirectory/results/thePlot_2.jpg
currentDirectory/results/thePlot_3.jpg
currentDirectory/results/thePlot_4.jpg
currentDirectory/results/thePlot_5.jpg
Rstudio中的.Rnw腳本將創建.tex文件,然後我可以運行pdflatex以生成包含這五個圖像的.pdf文件。下面是我曾嘗試:
\documentclass{article}
\usepackage{float, hyperref}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{caption}
\usepackage{algorithm}
\usepackage{algorithmic}
\begin{document}
\SweaveOpts{concordance=TRUE}
\author{myName}
\title{myTitle}
\maketitle
<<options, echo=FALSE>>=
library(knitr)
opts_chunk$set(cache=TRUE)
@
\section*{mySection}
\FOR{i in 1:5}
nPlots=i
plotName = "thePlot"
outDir = "results"
\includegraphics{paste(getwd(), "/", outDir , "/", plotName, "_", i, sep="")}
\ENDFOR
\end{document}
對於我收到幾個錯誤:
第25行:未定義的控制序列。 第29行:缺少$插入。 第29行:LaTeX錯誤:未找到文件`paste(getwd(),「/」,outDir,「/」,plotName,「_」,i,sep =「」)。 第29行:缺少$插入。 第30行:未定義的控制序列。
任何幫助非常感謝!
編輯1:我考慮到了亞歷克斯A.的建議,並改變了部分以包含\ Sexpr {}表達式如下:
\FOR{i in 1:5}
\Sexpr{nPlots=i}
\Sexpr{plotName = "thePlot"}
\Sexpr{outDir = "results"}
\includegraphics{\Sexpr{paste(getwd(), "/", outDir , "/", plotName, "_", i, sep="")}}
\ENDFOR
\end{document}
不過,現在我收到一個錯誤:
object 'i' not found
我試着在改變條件的for循環也包括\ Sexpr {}比如:
\FOR{\Sexpr{i in 1:5}}
但THI我得到了錯誤:
Unexpected 'in'
任何幫助表示讚賞!
編輯2:
我試着考慮建議乾脆把for循環和圖像插入RCODE。所以,我試圖用JPEG庫及其readJPEG方法,如下圖所示:
<<echo=FALSE>>==
library(jpeg)
@
<<plots, echo = FALSE, fig = TRUE, figs.only = TRUE, results = hide>>=
for (i in 1:5){
nPlots=i
plotName = "thePlot"
outDir = "results"
img <- readJPEG(paste(getwd(), "/", outDir , "/", plotName, "_", i, ".jpg", sep=""))
plot(img)
}
@
\end{document}
不幸的是,這還導致了錯誤:
unexpected 'in'
此外,當我單獨運行下面的代碼(未在for循環或.Rnw文件):
nPlots=1
plotName = "thePlot"
outDir = "results"
img <- readJPEG(paste(getwd(), "/", outDir , "/", plotName, "_", i, ".jpg", sep=""))
plot(img)
生成的圖像看起來比我所(位於currentDirectory所/結果/ thePlot_1.jpg)的.JPEG圖像
0不同
嘗試在'\ Sexpr {}'中包裝'粘貼(...)'。 –
@AlexA .:感謝您的幫助。它似乎確實解決了這個問題,儘管看起來for循環仍然不能像我所希望的那樣工作。你對這個新出現的錯誤有什麼建議嗎? – LanneR
我不認爲使用'\ For'和'\ EndFor'來包含多個圖是最好的方法。 (我其實不認爲你可以這樣做)。我可能會做一個R塊,比如'<< plot,echo = FALSE,fig = TRUE,figs.only = TRUE,results = hide >>'( R代碼來顯示圖)'@'。這會自動嵌入它們。 –