I got difference in output using "Knit to HTML" button and rmarkdown::render() which I figured out was related to environment. I'd like to know what exactly is the difference in environment so that I can fully understand what has happened. Here was my observation:
var1 <- ""
var1 <<- some code that creates a new value
With the above setting, the resulting observations are listed below. (The var needs to be pushed to global for a subsequent function to work. I know it's not a good practice, but a much quicker workaround than to figure out how to improve the function which has multiple nested functions.):
- run the chunks in Rstudio: the subsequent function gets the new var value and works
- "Knit to HTML" button: the subsequent function gets the new var value and works
- rmarkdown::render (in another file that calls the main code file): gets var="" and fails with this error message:
Error in approx(sp$y, sp$x, xout = cutoff) : need at least two non-NA values to interpolate
# then adding the additional line here made it work in rmarkdown::render()
var1 <- ""
var1 <<- some code that creates a new value
var1 <- same code to create the new value as above
- the subsequent function in all cases gets the new var value and work
Note that a previous chunk that uses the first setting (only save to global) did not get error in rmarkdown::render(). So what's the difference in the three ways of running the code in terms of environment?
ADDED later: I later found out that putting the arguments for the nested function in a list and call the function using do.call works in the rmarkdown::render() without using global variables. I give a simple example below. Why do.call makes a difference in the render call?
os1 <- function(OSdf, strata_name) {
form <- as.formula(paste("Surv(tte, status) ~", strata_name))
KMfit <- do.call(survfit, args = list(formula = form, data = OSdf, conf.type = "log-log"))
}