I am using a function within a function in R to create new variables. What I need is to be able to use these variables in the parent environment, BUT not global.
For instance, one solution is to use the global assignment operator <<-:
f1 <- function(x){
cat("X is ", x, "\n")
f2 <- function(){
cat("X will now be transfromed\n")
y <<- x + 4 # Use Global assignment
}
f2()
cat("Y is ", y, "\n")
}
f1(x = 5)
But I have over 20 variables, so this will clutter my workspace and is bad practice.
I was wondering if there is a better solution without having to play with concepts such as vars_to_parent <- new.env().
Is there is some elegant R sorcery where you have a new assignment operator, maybe something silly such as:
`<p-` <- function(){assign variable in such a way that its available in parent}
Which could help you to get these newly created variables to parent environment:
f1 <- function(x){
cat("X is ", x, "\n")
f2 <- function(){
cat("X will now be transfromed\n")
y <p- x + 4 # New cool assignment operator
}
f2()
cat("Y is ", y, "\n")
}
f1(x = 5)