Search code examples
rlatexrstudioknitrsweave

Conditionally insert Child using knitr


I'm trying to insert children into main.Rnw, as seen here:

<<child = here("child.Rnw") >>=
@

The Problem is, that child.Rnw isn't always needed. So I want to check if the file exists - if it does, it should be inserted, otherwise do nothing.

I tried the following:

# 1
\IfFileExists{./child.Rnw}{
    \Sexpr{knit_child(here("child.Rnw"))}
}{}

# 2 Try 
\iftrue\Sexpr{file.exists(here("Demofiles","Demopart.Rnw"))}{
    \Sexpr{knit_child(here("Demofiles","Demopart.Rnw"))}
}{} 

Both works, if the file exists, but deleting it gives the following error while compiling the PDF:

Error in readLines(if (is.character(input2))

The output reveals the following:

'child.Rnw' No such file or directory

Is there a way to conditionally input a child?


Solution

  • What about

    \Sexpr{if(file.exists("child.Rnw")) knit_child("child.Rnw")}
    

    ?