简体   繁体   中英

R | replace environment name by a variable

a newbie question: I want to write a universal function which saves variables in a new environment. The name of the environment I want to give as argument in to the function.

#create environment
my.env <- new.env()
#variable to store the name of the environment
env_n<-"my.env"
# now safe a  variable a with value 1 to my.env
my.env$a=1 #working

But I want to have a universal solution which works for many cases, there for I want to use the variable which stores the name of the environment. Something like:

#Things I tried
env_n$a=1 #not working
assign(a, 1, envir=env_n)

Can you help me? Thanks a lot!

The first parameter to assign() should be a character value, not a symbol. And the envir= parameter should be a proper environment, not a character value. If you want to get the value of a variable given a character value of the variable name, you use get() . This should work

assign("a", 1, envir=get(env_n))

But this is a very unusual operation for a "newbie" to be using. I would take a step back and look and what you are trying to do and see if there isn't a more "R-like" way to do things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM