Clark
Clark

Reputation: 1

Using variables defined in R environment within knitr

I'd like to use knitr to produce a document which includes numbers, tables, and figures defined separately in R. I have a separate .R script within which I define the variables of interest, and I have executed this script and verified the variables are in memory. Then, within a .Rmd file I have the R markup code, within which I attempt to display the variables I've defined in R. I keep getting error messages whenever I attempt to knit, stating something like:

Error in unique(c("AsIs", oldClass(x))) : object "lamdaQ6" not found...

Clearly the knitr process initiates a new environment which excludes already defined variables. I have rather extensive R code to define the variables I want to include in the document, which I want to keep separate from the R markup code (both for clarity, and because R markup is not a good development environment for R).

Is there some means of preserving awareness of existing variables in R memory within knitr? I have searched extensively and not found a solution, probably because I don't know the correct term.

Upvotes: 0

Views: 722

Answers (1)

Clark
Clark

Reputation: 1

The solution offered by Paul Roub worked -- I thought it didn't, but this turned-out to be due to my own typo.

A cleaner solution for my needs, rather than source the whole R file, was to use "save" to save just the objects I needed to create the document. I added a line to save the objects at the end of the .R file, then used "load" to load the objects at the top of the .Rmd script.

So, at the end of the .R file, to save objects XX and YY, I have:

save(XX,YY,file="Data4Rmd.RData")

Then, near the beginning of the .Rmd file, to import these objects, I have:

```

{r,echo=FALSE}

setwd("c:\CurrentProjectDirectory")

load(file="Data4Rmd.RData")

```

This allows me to later use statements like:

Decay rate is lambda = `r XX`, and mean lifetime is `r YY`.

Yet another alternative might have been to save and load the whole workspace, but this seemed excessive.

Thanks for the assistance Paul, much appreciated :)

Upvotes: 0

Related Questions