Justin Thong
Justin Thong

Reputation: 361

Assign variable in Parent Environment of a function

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

Upvotes: 4

Views: 5434

Answers (2)

noNameTed
noNameTed

Reputation: 307

This should do what you are asking for.

make.var<-function(){
   assign("holder", rep(NA,10))
}

If you want to set it using environments higher up the chain to the global environment you can the pos argument of assign.

Upvotes: 0

Mstislav Toivonen
Mstislav Toivonen

Reputation: 116

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()

Upvotes: 8

Related Questions