Ah, that 2% worry was actually confirmed - the entire enclosing environment chain is retained, not just access to the enclosing scope and the global env
http://adv-r.had.co.nz/Environments.html
# in global scope
RNGkind("L'Ecuyer-CMRG")
set.seed(101)
mc.reset.stream()
outside_var <- "outside"
# fake sim function
sim <- function(i,N,om1,om2) {
inside_var <- "inside_sim"
inside_func <- function(){
completely_inside <- "completely_inside"
data.frame(i, N, om1, om2, outside_var, inside_var, completely_inside)
}
return(inside_func())
}
As to the seed setting, I did some more digging after thinking more about design you have - and now I realized - the global set.seed call is being referenced I think, rather than the local set.seed inside the reactive expression
See this gist for an example:
# enclosing environment on function creation is globally, so the chain goes up to the global seed
sim <- function(i,N,om1,om2) {
inside_var <- "inside_sim"
inside_func <- function(){
completely_inside <- "completely_inside"
data.frame(i, N, om1, om2, outside_var, inside_var, completely_inside, seed)
}
return(inside_func())
}
server<-function(input, output) {
output$table <- renderTable({
seed <- "server_seed"
mclapply(1:input$n,
mc.cores=input$mccores,
sim,input$N,input$OM1,input$OM2) %>% bind_rows
})
}
Further, the seed <- "server_seed" is actually not at all in the chain of environments for the sim function, therefore has no impact on it (to the point of actually removing the global seed reference will cause the function to crashing saying can't find seed anywhere)
takeaway - if you are declaring a function in the global scope, but using it in an apply call/ any other place to invoke it, any part of that closure will not be accessed by the invoked function, rather it will reference its own scope chain where it was declared
hence, the only way to get the local seed is to also declare the sim function in that scope
server<-function(input, output) {
output$table <- renderTable({
seed <- "server_seed"
sim <- function(i,N,om1,om2) {
inside_var <- "inside_sim"
inside_func <- function(){
completely_inside <- "completely_inside"
data.frame(i, N, om1, om2, outside_var, inside_var, completely_inside, seed)
}
return(inside_func())
}
mclapply(1:input$n,
mc.cores=input$mccores,
sim,input$N,input$OM1,input$OM2) %>% bind_rows
})
}
Devin