Search code examples
rknitrsweaver-exams

Source R into chunk


I'm a new in exams so maybe this question is very newbie.

I can't source external R-file (contains re-usable functions) into my .Rnw.

MWE:

functions.r:

x <- 10

question.Rnw

<<echo=FALSE>>=
source('functions.r')
@
\begin{question}
  $x=\Sexpr{x}$
\end{question}

generate.r

library('exams')

exams2moodle('question.Rnw')

When I try Rscript generate.r:

Loading required namespace: rmarkdown

Error:  chunk 1 
Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'functions.r': No such file or directory
Execution halted

How can I re-use own R-functions in some questions?


Solution

  • All exercises are copied to a temporary directory where they are processed. Thus, you are in a different directory when you make the source() call. So either you need to include it with the full path source("/path/to/functions.r") - or alternatively you can copy the file to the temporary directory. There is a convenience function include_supplement() to do the latter. If functions.r is in the same directory as question.Rnw you simply need to do:

    include_supplement("functions.r")
    source("functions.r")
    

    in the code chunk at the beginning of question.Rnw.