4

This is similar to How to source R Markdown file like `source('myfile.r')`? with the following difference: I want my markdown file to generate an R script for future sourcing. The previous question was interested in directly sourcing the markdown file (which doesn't seem easy to do at this point).

Compiling an .Rmd markdown file that generates a useable source R file is possible by including the following:

```{r, ignore = TRUE, include = FALSE}
knit('markdown_file.Rmd', 'source_file.R', tangle = T)
```

This creates a source_file.R perfectly fine BUT it contains the knit call at the end. So when I source("source_file.R) in a different script, it recreates and overwrites itself, which seems like bad practice. Is there anyway to tell knit to ignore a chunk of code in the .Rmd file?

Community
  • 1
  • 1
bmayer
  • 426
  • 3
  • 9
  • 1
    I'm not sure I understand the question. Doesn't `eval=FALSE` work for this situation? – Brian P Jan 07 '15 at 01:51
  • `eval = F` doesn't work because then `knit` is not called and the source_file.R file is not created. My goal is to automate a process so that when the .Rmd file is compiled (to pdf), there is a companion .R source file created to be used by other scripts. – bmayer Feb 04 '15 at 18:40

1 Answers1

1

I solved this using a bash script and removing that knit snippet entirely from the R script.

Rscript -e 'knitr::knit("markdown_file.Rmd", "source_file.R", tangle = T)'

So with this approach, I could use similar bash script to knit my .Rmd into desired documentation output (like a pdf, code not shown), then this line of code to create an R file that can be sourced for use by other R scripts. Effectively, I'm removing the need to call knit within the Rmd file (or within RStudio).

bmayer
  • 426
  • 3
  • 9