Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sourcing external R scripts that rely on a variable set in the master/main Shiny document

I have just installed the preview release of RStudio, Version 0.98.864 (May 24th, 2014). Also, I have installed the development versions of knitr and shiny, via

devtools::install_github(c("yihui/knitr", "rstudio/shiny"))

I am trying to create a Shiny Document (using Rstudio dialog with Shiny Document template) to:

1) Set the value of a variable, e.g. x. The following code is the contents of my Rmd file: (I have to place this as an image as the formatting is playing up) enter image description here

2) Source an R script (testExternalisation.R) in the same directory that uses the variable, x, set in the .Rmd file; code as follows:

y <- x + 3

However, on running the .Rmd document I get the following message: "Error: object 'x' not found. Now, if I remove the first 3 lines of my .Rmd file, i.e. the front matter for a Shiny html_document, I am perfectly able to knit the resulting .Rmd document. Is there a solution for sourcing external scripts in Shiny Documents that rely on variables in the calling Shiny Doc?

Edit: When knitting the document, environment() returns <environment: R_GlobalEnv> for both the .Rmd and .R files. However, when running the Shiny document, the .Rmd environment is <environment: 0x05828968> and source environment is <environment: R_GlobalEnv>, so I need to ensure the two are using the same environment ...

Thanks.

like image 751
user1420372 Avatar asked May 27 '14 03:05

user1420372


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.

How do I run an R script from another R script?

You can execute R script as you would normally do by using the Windows command line. If your R version is different, then change the path to Rscript.exe. Use double quotes if the file path contains space.

What is r Markdown what are the features of r Markdown?

R Markdown provides an unified authoring framework for data science, combining your code, its results, and your prose commentary. R Markdown documents are fully reproducible and support dozens of output formats, like PDFs, Word files, slideshows, and more.

What is r Markdown used for?

R Markdown is a file format for making dynamic documents with R. An R Markdown document is written in markdown (an easy-to-write plain text format) and contains chunks of embedded R code, like the document below.


1 Answers

The following seems to solve the problem: change the source() function to

source("testExternalisation.R", local=environment())
like image 100
user1420372 Avatar answered Nov 03 '22 22:11

user1420372