I'm searching for a way to reuse r-code in latex using knitr. I have multiple excel documents, that I want to import, analyze and plot in the same way throughout my thesis. Right now I am making a new .rnw file for each excel document that I have. This means, that if I want to change anything, I have to do it in every .rnw file - which seems like the wrong approach. Is there a way, where I can call one .rnw file from the parent .rnw and providing it with an excel filename to import and work with.
Asked
Active
Viewed 562 times
2 Answers
1
Yes there is. You can use both the params
and render
function to help with this. If you are unfamiliar with parameters look here params and here for render. I wrote iris and mtcars to excel for the examples below. In the markdown below I call the excel parameter in the chunk which is the excel file and just print the first 10 rows.
---
title: "iris"
output: pdf_document
params:
excel: "G:/iris2.xlsx"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r cars}
head(xlsx::read.xlsx(params$excel,sheetIndex = 1))
```
Now to change the excel file you can use lapply
and the render function in a .R file.
#create list of excel files
exldocs <- c("G:/mtcars2.xlsx", "G:/iris2.xlsx")
#call the renders.rmd (above), pass the list of excel files to overwrite the #default param field, output a new pdf (call it whatever you want)
lapply(exldocs, function(x){
rmarkdown::render("G:/renders.Rmd", params = list(excel = x),
output_file =paste0(substr(x,1,nchar(x)-4),"pdf")
)})

Mike
- 3,797
- 1
- 11
- 30
-
This is in markdown. I have written it in rnw. Is there an alternative? :) or should i just start using markdown in stead – Christian Olesen Mar 29 '18 at 16:10
-
Good question - sorry I thought your question said rmd. I do not have the rnw solution. However if you are interested in switching easily to rmd check out this function from the `knitr` package `knitr::Sweave2knitr()`. Maybe also check out `knitr::render_sweave`. – Mike Mar 29 '18 at 17:00
0
You can use knitr::knit
and use the envir
argument as follows. Here is the .Rnw
file
% parameterized_reports.Rnw
\documentclass{article}
\begin{document}
<<>>=
foo
@
\end{document}
Here is the R code
tmp <- environment()
tmp$foo <- "xyz"
knitr::knit("parameterized_reports.Rnw", envir = tmp, output = "output.tex")
tools::texi2pdf("output.tex")
system('open output.pdf')
The result is

Benjamin Christoffersen
- 4,703
- 15
- 37