Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign variable in Parent Environment of a function

Tags:

r

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".

like image 355
Justin Thong Avatar asked Oct 25 '25 00:10

Justin Thong


1 Answers

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()
like image 139
Mstislav Toivonen Avatar answered Oct 27 '25 15:10

Mstislav Toivonen