Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making knitr run a r script: do I use read_chunk or source?

Tags:

I am running R version 2.15.3 with RStudio version 0.97.312. I have one script that reads my data from various sources and creates several data.tables. I then have another r script which uses the data.tables created in the first script. I wanted to turn the second script into a R markdown script so that the results of analysis can be outputted as a report.

I do not know the purpose of read_chunk, as opposed to source. My read_chunk is not working, but source is working. With either instance I do not get to see the objects in my workspace panel of RStudio.

Please explain the difference between read_chunk and source? Why would I use one or the other? Why will my .Rmd script not work

Here is ridiculously simplified sample

It does not work. I get the following message

Error: object 'z' not found

Two simple files...

test of source to rmd.R

x <- 1:10 y <- 3:4 z <- x*y   

testing source.Rmd

Can I run another script from Rmd ========================================================  Testing if I can run "test of source to rmd.R"  ```{r first part} require(knitr) read_chunk("test of source to rmd.R") a <- z-1000 a ```  The above worked only if I replaced "read_chunk" with "source". I  can use the vectors outside of the code chunk as in inline usage.  So here I will tell you that the first number is `r a[1]`. The most  interesting thing is that I cannot see the variables in RStudio  workspace but it must be there somewhere. 
like image 464
Farrel Avatar asked Mar 19 '13 14:03

Farrel


People also ask

Can you source R markdown?

To share R code like function definitions, you can put this code in an R script and import it in each file with the function source() To share common R Markdown text and code chunks, you can use child documents.

What is knitr in RMarkdown?

RMarkdown is an extension to markdown which includes the ability to embed code chunks and several other extensions useful for writing technical reports. The rmarkdown package extends the knitr package to, in one step, allow conversion between an RMarkdown file (.Rmd) into PDF, HTML, word document, amongst others.

How do you enter code in R?

You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS). There are a large number of chunk options in knitr documented at https://yihui.name/knitr/options.


1 Answers

read_chunk() only reads the source code (for future references); it does not evaluate code like source(). The purpose of read_chunk() was explained in this page as well as the manual.

like image 163
Yihui Xie Avatar answered Sep 30 '22 12:09

Yihui Xie