Look at example below, I have assigned variable holder to the global environment. However, I want to assign holder exclusively to the local environment of make.var(). How do I do so?
make.var<-function(){
holder<<-rep(NA,10) #assigns global
}
test<-function(){
make.var()
}
EDIT: I think the term that is frequently used "calling environment" as opposed to "parent environment".
You can get a calling environment using parent.frame (don't confuse it with parent.env) and assign variables to it using $ or [[ (as you do with lists).
Or you can use assign.
E.g.
rm(list = ls())
`%<-1%` <- function(x, y) { p <- parent.frame() ; p[[deparse(substitute(x))]] <- y }
`%<-2%` <- function(x, y) { assign(deparse(substitute(x)), y, env = parent.frame())}
And then:
ls()
a1 %<-1% 111
ls()
a2 %<-2% 222
ls()
a1 ; a2
test1 <- function(x) { print(ls()); t %<-1% x; print(ls()); t }
test2 <- function(x) { print(ls()); t %<-2% x; print(ls()); t }
ls()
test1(333)
ls()
test2(444)
ls()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With