library(learnr)

Section 1

The best way to reproduce the effects described in this tutorial is to run this code and then work through the tutorial:

foo <- "Remember me." # this will be significant

devtools::install_github("rstudio-education/gradethis")
learnr::run_tutorial("scoping-rules", package = "gradethis")

Knitr chunks

Where does knitr save the results of code chunks? In the global environment of a fresh R session. Notice that foo does not exist in this session.

knitr_obj <- "I was created in a knitr chunk."
environment()
ls.str(environment())

What's in scope?

Which environments are in scope for a learnr exercise chunk? Not the environment above.

Exercise chunks will be evaluated in the R session that calls learnr::run_tutorial. This will be your current R Session, not the fresh one that R Markdown generates. Everything in your global environment will be in scope and hence available to the exercise chunks---like foo!

environment()
parent.env(environment())
ls.str(parent.env(environment()))

The big exception

If a tutorial is launched from the RStudio IDE GUI by clicking the Run Document button, the exercise chunks will be evaluated in the fresh R process.

As a result, the objects in your global environment will not be available when you run an exercise. However, the objects in the global environment of the fresh R session will be available. This includes everything created by a knitr code chunk.

To try this, close the tutorial and then run this code and click the Run Document button.

rstudioapi::navigateToFile(system.file("tutorials", "scoping-rules/scoping-rules.Rmd", package = "gradethis"))

The third case

If you publish the tutorial to shinyapps.io, the exercise chunks will have access to neither the objects in your current global environment nor the objects created by knitr code chunks. Here they truly are run in a clean scope, e.g.

https://tutorials.shinyapps.io/scoping-rules/



rstudio-education/grader documentation built on July 6, 2023, 8:48 a.m.