tl;dr My functions need variables assigned to the global environment when I evaluate them in a sub environment like map, I don't want this help plzzz.
To make my functions more flexible I have made some function that take other functions as arguments, this allows the overall function framework to be the same across multiple uses and makes maintenance a lot easier. However I am getting issues with the evaluation environments. After reading this I asked a question on SO but didn't get any satisfactory answers and so hope that I might be able to solve my problem here.
library(dplyr);library(rlang)
OtherStuff <-c(10, NA)
#This quo of mean takes the vector "otherStuff" and the as yet undefined variable "vector"
EvaluateThisNow <-quo(mean(c(vector,OtherStuff), na.rm = TRUE))
MyFunc <- function(vector, TheFunction){
#uses the captire environment which doesn't contain the object vector
print(get_env(TheFunction))
#Reset the enivronment of TheFunction to the current environment where vector exists
TheFunction<- set_env(TheFunction, get_env())
print(get_env(TheFunction))
#The supplied function is now evaluated inside the MyFunc environment using "OtherStuff" and the variable "vector" which is defined inside MyFunc
print(TheFunction)
TheFunction %>%
eval_tidy
}
MyFunc(1:4, EvaluateThisNow)
So far so good, however when I start trying to evaluate the above in a different environment it doesn't work.
#The Problem is if that process takes place inside something else then the system breaks down as now OtherStuff is not defined in the global environment but inside a local environment.
rm(OtherStuff)
set.seed(123)
1:3 %>% map(~{
#assigned inside local environment
OtherStuff <-c(sample(1:10, 1), NA)
EvaluateThis <-quo(mean(c(vector,OtherStuff), na.rm = TRUE))
MyFunc(1:4, EvaluateThis)
})
#assigning the values to the global environment solves the problem, but isn't ideal and I thought that scoping would have avoided this problem.
set.seed(123)
1:3 %>% map(~{
#assigned inside local environment
OtherStuff <<-c(sample(1:10, 1), NA)
EvaluateThis <-quo(mean(c(vector,OtherStuff), na.rm = TRUE))
MyFunc(1:4, EvaluateThis)
})
#The problem also occurs when using the inputs of map
OtherStuff <-c(10, NA)
c(TRUE, FALSE, TRUE) %>% map(~{
val <- .x
print(val)
EvaluateThis <-quo(mean(c(vector,OtherStuff), na.rm = val))
MyFunc(1:4, EvaluateThis)
})
How do I get the scoping to work so that the function looks into the environment it is called in to find variables that aren't defined within its environment before looiking into the global environment.