How do I avoid eval and parse?Avoiding the infamous “eval(parse())” constructR: eval(parse(…)) is often suboptimalWhy is using the JavaScript eval function a bad idea?When is JavaScript's eval() not evil?How to sort a dataframe by multiple column(s)How to join (merge) data frames (inner, outer, left, right)What's the difference between eval, exec, and compile?How to make a great R reproducible exampleWhat does Python's eval() do? Avoiding the infamous “eval(parse())” constructUse argument value as variable name in R during function runR: eval parse function call not accessing correct environments

Why is making salt water prohibited on Shabbat?

How to answer pointed "are you quitting" questioning when I don't want them to suspect

What to wear for invited talk in Canada

What does "enim et" mean?

Why do we use polarized capacitors?

How to move the player while also allowing forces to affect it

I see my dog run

Can I legally use front facing blue light in the UK?

Are white and non-white police officers equally likely to kill black suspects?

Mapping arrows in commutative diagrams

Is "plugging out" electronic devices an American expression?

How to manage monthly salary

Is it legal to have the "// (c) 2019 John Smith" header in all files when there are hundreds of contributors?

Are cabin dividers used to "hide" the flex of the airplane?

Why airport relocation isn't done gradually?

What is the meaning of "of trouble" in the following sentence?

Why is my log file so massive? 22gb. I am running log backups

Could Giant Ground Sloths have been a Good Pack Animal for the Ancient Mayans

Where to refill my bottle in India?

Patience, young "Padovan"

What is GPS' 19 year rollover and does it present a cybersecurity issue?

Latin words with no plurals in English

Travelling to Edinburgh from India

Prime joint compound before latex paint?



How do I avoid eval and parse?


Avoiding the infamous “eval(parse())” constructR: eval(parse(…)) is often suboptimalWhy is using the JavaScript eval function a bad idea?When is JavaScript's eval() not evil?How to sort a dataframe by multiple column(s)How to join (merge) data frames (inner, outer, left, right)What's the difference between eval, exec, and compile?How to make a great R reproducible exampleWhat does Python's eval() do? Avoiding the infamous “eval(parse())” constructUse argument value as variable name in R during function runR: eval parse function call not accessing correct environments






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








14















I have written a function that sources files that contain scripts for other functions and stores these functions in an alternative environment so that they aren't cluttering up the global environment. The code works, but contains three instances of eval(parse(...)):



# sourceFunctionHidden ---------------------------
# source a function and hide the function from the global environment
sourceFunctionHidden <- function(functions, environment = "env", ...)
if (environment %in% search())
while (environment %in% search())
if (!exists("counter", inherits = F)) counter <- 0
eval(parse(text = paste0("detach(", environment, ")")))
counter <- counter + 1

cat("detached", counter, environment, "sn")
else cat("no", environment, "attachedn")
if (!environment %in% ls(.GlobalEnv, all.names = T))
assign(environment, new.env(), pos = .GlobalEnv)
cat("created", environment, "n")
else cat(environment, "already existsn")
sapply(functions, function(func)
source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
eval(parse(text = paste0(environment, "$", func," <- ", func)))
cat(func, "created in", environment, "n")
)
eval(parse(text = paste0("attach(", environment, ")")))
cat("attached", environment, "nn")



Much has been written about the sub-optimality of the eval(parse(...)) construction (see here and here). However, the discussions that I've found mostly deal with alternate strategies for subsetting. The first and third instances of eval(parse(...)) in my code don't involve subsetting (the second instance might be related to subsetting).



Is there a way to call new.env(...), [environment name]$[function name] <- [function name], and attach(...) without resorting to eval(parse(...))? Thanks.



N.B.: I don't want to change the names of my functions to .name to hide them in the global environment










share|improve this question



















  • 1





    Just discovered that eval(parse(text = paste0("detach(", environment, ")"))) can be replaced with detach(environment, character.only = T). The question about improving eval(parse(text = paste0("attach(", environment, ")"))) remains.

    – Josh
    Mar 30 at 2:03


















14















I have written a function that sources files that contain scripts for other functions and stores these functions in an alternative environment so that they aren't cluttering up the global environment. The code works, but contains three instances of eval(parse(...)):



# sourceFunctionHidden ---------------------------
# source a function and hide the function from the global environment
sourceFunctionHidden <- function(functions, environment = "env", ...)
if (environment %in% search())
while (environment %in% search())
if (!exists("counter", inherits = F)) counter <- 0
eval(parse(text = paste0("detach(", environment, ")")))
counter <- counter + 1

cat("detached", counter, environment, "sn")
else cat("no", environment, "attachedn")
if (!environment %in% ls(.GlobalEnv, all.names = T))
assign(environment, new.env(), pos = .GlobalEnv)
cat("created", environment, "n")
else cat(environment, "already existsn")
sapply(functions, function(func)
source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
eval(parse(text = paste0(environment, "$", func," <- ", func)))
cat(func, "created in", environment, "n")
)
eval(parse(text = paste0("attach(", environment, ")")))
cat("attached", environment, "nn")



Much has been written about the sub-optimality of the eval(parse(...)) construction (see here and here). However, the discussions that I've found mostly deal with alternate strategies for subsetting. The first and third instances of eval(parse(...)) in my code don't involve subsetting (the second instance might be related to subsetting).



Is there a way to call new.env(...), [environment name]$[function name] <- [function name], and attach(...) without resorting to eval(parse(...))? Thanks.



N.B.: I don't want to change the names of my functions to .name to hide them in the global environment










share|improve this question



















  • 1





    Just discovered that eval(parse(text = paste0("detach(", environment, ")"))) can be replaced with detach(environment, character.only = T). The question about improving eval(parse(text = paste0("attach(", environment, ")"))) remains.

    – Josh
    Mar 30 at 2:03














14












14








14








I have written a function that sources files that contain scripts for other functions and stores these functions in an alternative environment so that they aren't cluttering up the global environment. The code works, but contains three instances of eval(parse(...)):



# sourceFunctionHidden ---------------------------
# source a function and hide the function from the global environment
sourceFunctionHidden <- function(functions, environment = "env", ...)
if (environment %in% search())
while (environment %in% search())
if (!exists("counter", inherits = F)) counter <- 0
eval(parse(text = paste0("detach(", environment, ")")))
counter <- counter + 1

cat("detached", counter, environment, "sn")
else cat("no", environment, "attachedn")
if (!environment %in% ls(.GlobalEnv, all.names = T))
assign(environment, new.env(), pos = .GlobalEnv)
cat("created", environment, "n")
else cat(environment, "already existsn")
sapply(functions, function(func)
source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
eval(parse(text = paste0(environment, "$", func," <- ", func)))
cat(func, "created in", environment, "n")
)
eval(parse(text = paste0("attach(", environment, ")")))
cat("attached", environment, "nn")



Much has been written about the sub-optimality of the eval(parse(...)) construction (see here and here). However, the discussions that I've found mostly deal with alternate strategies for subsetting. The first and third instances of eval(parse(...)) in my code don't involve subsetting (the second instance might be related to subsetting).



Is there a way to call new.env(...), [environment name]$[function name] <- [function name], and attach(...) without resorting to eval(parse(...))? Thanks.



N.B.: I don't want to change the names of my functions to .name to hide them in the global environment










share|improve this question
















I have written a function that sources files that contain scripts for other functions and stores these functions in an alternative environment so that they aren't cluttering up the global environment. The code works, but contains three instances of eval(parse(...)):



# sourceFunctionHidden ---------------------------
# source a function and hide the function from the global environment
sourceFunctionHidden <- function(functions, environment = "env", ...)
if (environment %in% search())
while (environment %in% search())
if (!exists("counter", inherits = F)) counter <- 0
eval(parse(text = paste0("detach(", environment, ")")))
counter <- counter + 1

cat("detached", counter, environment, "sn")
else cat("no", environment, "attachedn")
if (!environment %in% ls(.GlobalEnv, all.names = T))
assign(environment, new.env(), pos = .GlobalEnv)
cat("created", environment, "n")
else cat(environment, "already existsn")
sapply(functions, function(func)
source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
eval(parse(text = paste0(environment, "$", func," <- ", func)))
cat(func, "created in", environment, "n")
)
eval(parse(text = paste0("attach(", environment, ")")))
cat("attached", environment, "nn")



Much has been written about the sub-optimality of the eval(parse(...)) construction (see here and here). However, the discussions that I've found mostly deal with alternate strategies for subsetting. The first and third instances of eval(parse(...)) in my code don't involve subsetting (the second instance might be related to subsetting).



Is there a way to call new.env(...), [environment name]$[function name] <- [function name], and attach(...) without resorting to eval(parse(...))? Thanks.



N.B.: I don't want to change the names of my functions to .name to hide them in the global environment







r eval






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 30 at 3:31







Josh

















asked Mar 29 at 22:03









JoshJosh

337113




337113







  • 1





    Just discovered that eval(parse(text = paste0("detach(", environment, ")"))) can be replaced with detach(environment, character.only = T). The question about improving eval(parse(text = paste0("attach(", environment, ")"))) remains.

    – Josh
    Mar 30 at 2:03













  • 1





    Just discovered that eval(parse(text = paste0("detach(", environment, ")"))) can be replaced with detach(environment, character.only = T). The question about improving eval(parse(text = paste0("attach(", environment, ")"))) remains.

    – Josh
    Mar 30 at 2:03








1




1





Just discovered that eval(parse(text = paste0("detach(", environment, ")"))) can be replaced with detach(environment, character.only = T). The question about improving eval(parse(text = paste0("attach(", environment, ")"))) remains.

– Josh
Mar 30 at 2:03






Just discovered that eval(parse(text = paste0("detach(", environment, ")"))) can be replaced with detach(environment, character.only = T). The question about improving eval(parse(text = paste0("attach(", environment, ")"))) remains.

– Josh
Mar 30 at 2:03













3 Answers
3






active

oldest

votes


















5














For what its worth, the function source actually uses eval(parse(...)), albeit in a somewhat subtle way. First, .Internal(parse(...)) is used to create expressions, which after more processing are later passed to eval. So eval(parse(...)) seems to be good enough for the R core team in this instance.



That said, you don't need to jump through hoops to source functions into a new environment. source provides an argument local that can be used for precisely this.




local: TRUE, FALSE or an environment, determining where the parsed expressions are evaluated.




An example:



env = new.env()
source('test.r', local = env)


testing it works:



env$test('hello', 'world')
# [1] "hello world"
ls(pattern = 'test')
# character(0)


And an example test.r file to use this on:



test = function(a,b) paste(a,b)





share|improve this answer























  • Thank you, I missed that aspect of source(). However, if I change that line of code to source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) I get the error Error in source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) : 'local' must be TRUE, FALSE or an environment. Is there a way to convert the "env" that comes from environment to env?

    – Josh
    Mar 30 at 2:11












  • You should create an environment to save into. For example as I demonstrated with env = new.env(). Then pass the environment as your argument. If you need to name the new environement using a character string (environemt in your example - although it is bad practice to use reserved words as names), you can use assign(environment, new.env())

    – dww
    Mar 30 at 2:34


















3














If you want to keep it off global_env, put it into a package. It's common for people in the R community to put a bunch of frequently used helper functions into their own personal package.






share|improve this answer























  • I agree. I eventually need to learn how to do this.

    – Josh
    Mar 30 at 2:04






  • 1





    It's not as hard you think! I think the function you're trying to write is a lot harder and more complicated. Lots of tutorials to write packages out there.

    – thc
    Mar 30 at 3:49












  • I haven't had time to make a package yet, but if this description of how easy it is is accurate, holy crap! I'm going to make everything into a package!

    – Josh
    Mar 30 at 4:04



















0














tl;dr: The right way to convert quoted strings to object names is to use assign() and get(). See this post.



The long answer: The answer from @dww about being able to source() directly to a specific environment led me to change the second instance of eval(parse(...)) as follows:



# old version
source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
eval(parse(text = paste0(environment, "$", func," <- ", func)))
# new version
source(
paste0("C:/Users/JT/R/Functions/", func, ".R"),
local = get(environment)
)


The answer from @dww also got me to exploring attach(). attach() has an argument that allows specification of the environment to which to direct the output. This led me to change the third instance of eval(parse(...)) (below). Note the use of get() to convert the "env" that comes from environment to the unquoted env that attach() requires.



# old version
eval(parse(text = paste0("attach(", environment, ")")))
# new version
attach(get(environment), name = environment)


Finally, at some point in this process I was reminded that rm() has a character.only argument. detach() accepts the same argument, so I changed the second instance of eval(parse()) as below:



# old version
eval(parse(text = paste0("detach(", environment, ")")))
# new version
detach(environment, character.only = T)


So my new code is:



# sourceFunctionHidden ---------------------------
# source a function and hide the function from the global environment
sourceFunctionHidden <- function(functions, environment = "env", ...)
if (environment %in% search())
while (environment %in% search())
if (!exists("counter", inherits = F)) counter <- 0
detach(environment, character.only = T)
counter <- counter + 1

cat("detached", counter, environment, "sn")
else cat("no", environment, "attachedn")
if (!environment %in% ls(.GlobalEnv, all.names = T))
assign(environment, new.env(), pos = .GlobalEnv)
cat("created", environment, "n")
else cat(environment, "already existsn")
sapply(functions, function(func)
source(
paste0("C:/Users/JT/R/Functions/", func, ".R"),
local = get(environment)
)
cat(func, "created in", environment, "n")
)
attach(get(environment), name = environment)
cat("attached", environment, "nn")






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55426015%2fhow-do-i-avoid-eval-and-parse%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    5














    For what its worth, the function source actually uses eval(parse(...)), albeit in a somewhat subtle way. First, .Internal(parse(...)) is used to create expressions, which after more processing are later passed to eval. So eval(parse(...)) seems to be good enough for the R core team in this instance.



    That said, you don't need to jump through hoops to source functions into a new environment. source provides an argument local that can be used for precisely this.




    local: TRUE, FALSE or an environment, determining where the parsed expressions are evaluated.




    An example:



    env = new.env()
    source('test.r', local = env)


    testing it works:



    env$test('hello', 'world')
    # [1] "hello world"
    ls(pattern = 'test')
    # character(0)


    And an example test.r file to use this on:



    test = function(a,b) paste(a,b)





    share|improve this answer























    • Thank you, I missed that aspect of source(). However, if I change that line of code to source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) I get the error Error in source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) : 'local' must be TRUE, FALSE or an environment. Is there a way to convert the "env" that comes from environment to env?

      – Josh
      Mar 30 at 2:11












    • You should create an environment to save into. For example as I demonstrated with env = new.env(). Then pass the environment as your argument. If you need to name the new environement using a character string (environemt in your example - although it is bad practice to use reserved words as names), you can use assign(environment, new.env())

      – dww
      Mar 30 at 2:34















    5














    For what its worth, the function source actually uses eval(parse(...)), albeit in a somewhat subtle way. First, .Internal(parse(...)) is used to create expressions, which after more processing are later passed to eval. So eval(parse(...)) seems to be good enough for the R core team in this instance.



    That said, you don't need to jump through hoops to source functions into a new environment. source provides an argument local that can be used for precisely this.




    local: TRUE, FALSE or an environment, determining where the parsed expressions are evaluated.




    An example:



    env = new.env()
    source('test.r', local = env)


    testing it works:



    env$test('hello', 'world')
    # [1] "hello world"
    ls(pattern = 'test')
    # character(0)


    And an example test.r file to use this on:



    test = function(a,b) paste(a,b)





    share|improve this answer























    • Thank you, I missed that aspect of source(). However, if I change that line of code to source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) I get the error Error in source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) : 'local' must be TRUE, FALSE or an environment. Is there a way to convert the "env" that comes from environment to env?

      – Josh
      Mar 30 at 2:11












    • You should create an environment to save into. For example as I demonstrated with env = new.env(). Then pass the environment as your argument. If you need to name the new environement using a character string (environemt in your example - although it is bad practice to use reserved words as names), you can use assign(environment, new.env())

      – dww
      Mar 30 at 2:34













    5












    5








    5







    For what its worth, the function source actually uses eval(parse(...)), albeit in a somewhat subtle way. First, .Internal(parse(...)) is used to create expressions, which after more processing are later passed to eval. So eval(parse(...)) seems to be good enough for the R core team in this instance.



    That said, you don't need to jump through hoops to source functions into a new environment. source provides an argument local that can be used for precisely this.




    local: TRUE, FALSE or an environment, determining where the parsed expressions are evaluated.




    An example:



    env = new.env()
    source('test.r', local = env)


    testing it works:



    env$test('hello', 'world')
    # [1] "hello world"
    ls(pattern = 'test')
    # character(0)


    And an example test.r file to use this on:



    test = function(a,b) paste(a,b)





    share|improve this answer













    For what its worth, the function source actually uses eval(parse(...)), albeit in a somewhat subtle way. First, .Internal(parse(...)) is used to create expressions, which after more processing are later passed to eval. So eval(parse(...)) seems to be good enough for the R core team in this instance.



    That said, you don't need to jump through hoops to source functions into a new environment. source provides an argument local that can be used for precisely this.




    local: TRUE, FALSE or an environment, determining where the parsed expressions are evaluated.




    An example:



    env = new.env()
    source('test.r', local = env)


    testing it works:



    env$test('hello', 'world')
    # [1] "hello world"
    ls(pattern = 'test')
    # character(0)


    And an example test.r file to use this on:



    test = function(a,b) paste(a,b)






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 30 at 0:15









    dwwdww

    16k32659




    16k32659












    • Thank you, I missed that aspect of source(). However, if I change that line of code to source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) I get the error Error in source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) : 'local' must be TRUE, FALSE or an environment. Is there a way to convert the "env" that comes from environment to env?

      – Josh
      Mar 30 at 2:11












    • You should create an environment to save into. For example as I demonstrated with env = new.env(). Then pass the environment as your argument. If you need to name the new environement using a character string (environemt in your example - although it is bad practice to use reserved words as names), you can use assign(environment, new.env())

      – dww
      Mar 30 at 2:34

















    • Thank you, I missed that aspect of source(). However, if I change that line of code to source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) I get the error Error in source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) : 'local' must be TRUE, FALSE or an environment. Is there a way to convert the "env" that comes from environment to env?

      – Josh
      Mar 30 at 2:11












    • You should create an environment to save into. For example as I demonstrated with env = new.env(). Then pass the environment as your argument. If you need to name the new environement using a character string (environemt in your example - although it is bad practice to use reserved words as names), you can use assign(environment, new.env())

      – dww
      Mar 30 at 2:34
















    Thank you, I missed that aspect of source(). However, if I change that line of code to source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) I get the error Error in source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) : 'local' must be TRUE, FALSE or an environment. Is there a way to convert the "env" that comes from environment to env?

    – Josh
    Mar 30 at 2:11






    Thank you, I missed that aspect of source(). However, if I change that line of code to source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) I get the error Error in source(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment) : 'local' must be TRUE, FALSE or an environment. Is there a way to convert the "env" that comes from environment to env?

    – Josh
    Mar 30 at 2:11














    You should create an environment to save into. For example as I demonstrated with env = new.env(). Then pass the environment as your argument. If you need to name the new environement using a character string (environemt in your example - although it is bad practice to use reserved words as names), you can use assign(environment, new.env())

    – dww
    Mar 30 at 2:34





    You should create an environment to save into. For example as I demonstrated with env = new.env(). Then pass the environment as your argument. If you need to name the new environement using a character string (environemt in your example - although it is bad practice to use reserved words as names), you can use assign(environment, new.env())

    – dww
    Mar 30 at 2:34













    3














    If you want to keep it off global_env, put it into a package. It's common for people in the R community to put a bunch of frequently used helper functions into their own personal package.






    share|improve this answer























    • I agree. I eventually need to learn how to do this.

      – Josh
      Mar 30 at 2:04






    • 1





      It's not as hard you think! I think the function you're trying to write is a lot harder and more complicated. Lots of tutorials to write packages out there.

      – thc
      Mar 30 at 3:49












    • I haven't had time to make a package yet, but if this description of how easy it is is accurate, holy crap! I'm going to make everything into a package!

      – Josh
      Mar 30 at 4:04
















    3














    If you want to keep it off global_env, put it into a package. It's common for people in the R community to put a bunch of frequently used helper functions into their own personal package.






    share|improve this answer























    • I agree. I eventually need to learn how to do this.

      – Josh
      Mar 30 at 2:04






    • 1





      It's not as hard you think! I think the function you're trying to write is a lot harder and more complicated. Lots of tutorials to write packages out there.

      – thc
      Mar 30 at 3:49












    • I haven't had time to make a package yet, but if this description of how easy it is is accurate, holy crap! I'm going to make everything into a package!

      – Josh
      Mar 30 at 4:04














    3












    3








    3







    If you want to keep it off global_env, put it into a package. It's common for people in the R community to put a bunch of frequently used helper functions into their own personal package.






    share|improve this answer













    If you want to keep it off global_env, put it into a package. It's common for people in the R community to put a bunch of frequently used helper functions into their own personal package.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 29 at 22:35









    thcthc

    5,43111224




    5,43111224












    • I agree. I eventually need to learn how to do this.

      – Josh
      Mar 30 at 2:04






    • 1





      It's not as hard you think! I think the function you're trying to write is a lot harder and more complicated. Lots of tutorials to write packages out there.

      – thc
      Mar 30 at 3:49












    • I haven't had time to make a package yet, but if this description of how easy it is is accurate, holy crap! I'm going to make everything into a package!

      – Josh
      Mar 30 at 4:04


















    • I agree. I eventually need to learn how to do this.

      – Josh
      Mar 30 at 2:04






    • 1





      It's not as hard you think! I think the function you're trying to write is a lot harder and more complicated. Lots of tutorials to write packages out there.

      – thc
      Mar 30 at 3:49












    • I haven't had time to make a package yet, but if this description of how easy it is is accurate, holy crap! I'm going to make everything into a package!

      – Josh
      Mar 30 at 4:04

















    I agree. I eventually need to learn how to do this.

    – Josh
    Mar 30 at 2:04





    I agree. I eventually need to learn how to do this.

    – Josh
    Mar 30 at 2:04




    1




    1





    It's not as hard you think! I think the function you're trying to write is a lot harder and more complicated. Lots of tutorials to write packages out there.

    – thc
    Mar 30 at 3:49






    It's not as hard you think! I think the function you're trying to write is a lot harder and more complicated. Lots of tutorials to write packages out there.

    – thc
    Mar 30 at 3:49














    I haven't had time to make a package yet, but if this description of how easy it is is accurate, holy crap! I'm going to make everything into a package!

    – Josh
    Mar 30 at 4:04






    I haven't had time to make a package yet, but if this description of how easy it is is accurate, holy crap! I'm going to make everything into a package!

    – Josh
    Mar 30 at 4:04












    0














    tl;dr: The right way to convert quoted strings to object names is to use assign() and get(). See this post.



    The long answer: The answer from @dww about being able to source() directly to a specific environment led me to change the second instance of eval(parse(...)) as follows:



    # old version
    source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
    eval(parse(text = paste0(environment, "$", func," <- ", func)))
    # new version
    source(
    paste0("C:/Users/JT/R/Functions/", func, ".R"),
    local = get(environment)
    )


    The answer from @dww also got me to exploring attach(). attach() has an argument that allows specification of the environment to which to direct the output. This led me to change the third instance of eval(parse(...)) (below). Note the use of get() to convert the "env" that comes from environment to the unquoted env that attach() requires.



    # old version
    eval(parse(text = paste0("attach(", environment, ")")))
    # new version
    attach(get(environment), name = environment)


    Finally, at some point in this process I was reminded that rm() has a character.only argument. detach() accepts the same argument, so I changed the second instance of eval(parse()) as below:



    # old version
    eval(parse(text = paste0("detach(", environment, ")")))
    # new version
    detach(environment, character.only = T)


    So my new code is:



    # sourceFunctionHidden ---------------------------
    # source a function and hide the function from the global environment
    sourceFunctionHidden <- function(functions, environment = "env", ...)
    if (environment %in% search())
    while (environment %in% search())
    if (!exists("counter", inherits = F)) counter <- 0
    detach(environment, character.only = T)
    counter <- counter + 1

    cat("detached", counter, environment, "sn")
    else cat("no", environment, "attachedn")
    if (!environment %in% ls(.GlobalEnv, all.names = T))
    assign(environment, new.env(), pos = .GlobalEnv)
    cat("created", environment, "n")
    else cat(environment, "already existsn")
    sapply(functions, function(func)
    source(
    paste0("C:/Users/JT/R/Functions/", func, ".R"),
    local = get(environment)
    )
    cat(func, "created in", environment, "n")
    )
    attach(get(environment), name = environment)
    cat("attached", environment, "nn")






    share|improve this answer





























      0














      tl;dr: The right way to convert quoted strings to object names is to use assign() and get(). See this post.



      The long answer: The answer from @dww about being able to source() directly to a specific environment led me to change the second instance of eval(parse(...)) as follows:



      # old version
      source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
      eval(parse(text = paste0(environment, "$", func," <- ", func)))
      # new version
      source(
      paste0("C:/Users/JT/R/Functions/", func, ".R"),
      local = get(environment)
      )


      The answer from @dww also got me to exploring attach(). attach() has an argument that allows specification of the environment to which to direct the output. This led me to change the third instance of eval(parse(...)) (below). Note the use of get() to convert the "env" that comes from environment to the unquoted env that attach() requires.



      # old version
      eval(parse(text = paste0("attach(", environment, ")")))
      # new version
      attach(get(environment), name = environment)


      Finally, at some point in this process I was reminded that rm() has a character.only argument. detach() accepts the same argument, so I changed the second instance of eval(parse()) as below:



      # old version
      eval(parse(text = paste0("detach(", environment, ")")))
      # new version
      detach(environment, character.only = T)


      So my new code is:



      # sourceFunctionHidden ---------------------------
      # source a function and hide the function from the global environment
      sourceFunctionHidden <- function(functions, environment = "env", ...)
      if (environment %in% search())
      while (environment %in% search())
      if (!exists("counter", inherits = F)) counter <- 0
      detach(environment, character.only = T)
      counter <- counter + 1

      cat("detached", counter, environment, "sn")
      else cat("no", environment, "attachedn")
      if (!environment %in% ls(.GlobalEnv, all.names = T))
      assign(environment, new.env(), pos = .GlobalEnv)
      cat("created", environment, "n")
      else cat(environment, "already existsn")
      sapply(functions, function(func)
      source(
      paste0("C:/Users/JT/R/Functions/", func, ".R"),
      local = get(environment)
      )
      cat(func, "created in", environment, "n")
      )
      attach(get(environment), name = environment)
      cat("attached", environment, "nn")






      share|improve this answer



























        0












        0








        0







        tl;dr: The right way to convert quoted strings to object names is to use assign() and get(). See this post.



        The long answer: The answer from @dww about being able to source() directly to a specific environment led me to change the second instance of eval(parse(...)) as follows:



        # old version
        source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
        eval(parse(text = paste0(environment, "$", func," <- ", func)))
        # new version
        source(
        paste0("C:/Users/JT/R/Functions/", func, ".R"),
        local = get(environment)
        )


        The answer from @dww also got me to exploring attach(). attach() has an argument that allows specification of the environment to which to direct the output. This led me to change the third instance of eval(parse(...)) (below). Note the use of get() to convert the "env" that comes from environment to the unquoted env that attach() requires.



        # old version
        eval(parse(text = paste0("attach(", environment, ")")))
        # new version
        attach(get(environment), name = environment)


        Finally, at some point in this process I was reminded that rm() has a character.only argument. detach() accepts the same argument, so I changed the second instance of eval(parse()) as below:



        # old version
        eval(parse(text = paste0("detach(", environment, ")")))
        # new version
        detach(environment, character.only = T)


        So my new code is:



        # sourceFunctionHidden ---------------------------
        # source a function and hide the function from the global environment
        sourceFunctionHidden <- function(functions, environment = "env", ...)
        if (environment %in% search())
        while (environment %in% search())
        if (!exists("counter", inherits = F)) counter <- 0
        detach(environment, character.only = T)
        counter <- counter + 1

        cat("detached", counter, environment, "sn")
        else cat("no", environment, "attachedn")
        if (!environment %in% ls(.GlobalEnv, all.names = T))
        assign(environment, new.env(), pos = .GlobalEnv)
        cat("created", environment, "n")
        else cat(environment, "already existsn")
        sapply(functions, function(func)
        source(
        paste0("C:/Users/JT/R/Functions/", func, ".R"),
        local = get(environment)
        )
        cat(func, "created in", environment, "n")
        )
        attach(get(environment), name = environment)
        cat("attached", environment, "nn")






        share|improve this answer















        tl;dr: The right way to convert quoted strings to object names is to use assign() and get(). See this post.



        The long answer: The answer from @dww about being able to source() directly to a specific environment led me to change the second instance of eval(parse(...)) as follows:



        # old version
        source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
        eval(parse(text = paste0(environment, "$", func," <- ", func)))
        # new version
        source(
        paste0("C:/Users/JT/R/Functions/", func, ".R"),
        local = get(environment)
        )


        The answer from @dww also got me to exploring attach(). attach() has an argument that allows specification of the environment to which to direct the output. This led me to change the third instance of eval(parse(...)) (below). Note the use of get() to convert the "env" that comes from environment to the unquoted env that attach() requires.



        # old version
        eval(parse(text = paste0("attach(", environment, ")")))
        # new version
        attach(get(environment), name = environment)


        Finally, at some point in this process I was reminded that rm() has a character.only argument. detach() accepts the same argument, so I changed the second instance of eval(parse()) as below:



        # old version
        eval(parse(text = paste0("detach(", environment, ")")))
        # new version
        detach(environment, character.only = T)


        So my new code is:



        # sourceFunctionHidden ---------------------------
        # source a function and hide the function from the global environment
        sourceFunctionHidden <- function(functions, environment = "env", ...)
        if (environment %in% search())
        while (environment %in% search())
        if (!exists("counter", inherits = F)) counter <- 0
        detach(environment, character.only = T)
        counter <- counter + 1

        cat("detached", counter, environment, "sn")
        else cat("no", environment, "attachedn")
        if (!environment %in% ls(.GlobalEnv, all.names = T))
        assign(environment, new.env(), pos = .GlobalEnv)
        cat("created", environment, "n")
        else cat(environment, "already existsn")
        sapply(functions, function(func)
        source(
        paste0("C:/Users/JT/R/Functions/", func, ".R"),
        local = get(environment)
        )
        cat(func, "created in", environment, "n")
        )
        attach(get(environment), name = environment)
        cat("attached", environment, "nn")







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 30 at 3:35

























        answered Mar 30 at 3:30









        JoshJosh

        337113




        337113



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55426015%2fhow-do-i-avoid-eval-and-parse%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Triangular numbers and gcdProving sum of a set is $0 pmod n$ if $n$ is odd, or $fracn2 pmod n$ if $n$ is even?Is greatest common divisor of two numbers really their smallest linear combination?GCD, LCM RelationshipProve a set of nonnegative integers with greatest common divisor 1 and closed under addition has all but finite many nonnegative integers.all pairs of a and b in an equation containing gcdTriangular Numbers Modulo $k$ - Hit All Values?Understanding the Existence and Uniqueness of the GCDGCD and LCM with logical symbolsThe greatest common divisor of two positive integers less than 100 is equal to 3. Their least common multiple is twelve times one of the integers.Suppose that for all integers $x$, $x|a$ and $x|b$ if and only if $x|c$. Then $c = gcd(a,b)$Which is the gcd of 2 numbers which are multiplied and the result is 600000?

            Ingelân Ynhâld Etymology | Geografy | Skiednis | Polityk en bestjoer | Ekonomy | Demografy | Kultuer | Klimaat | Sjoch ek | Keppelings om utens | Boarnen, noaten en referinsjes Navigaasjemenuwww.gov.ukOffisjele webside fan it regear fan it Feriene KeninkrykOffisjele webside fan it Britske FerkearsburoNederlânsktalige ynformaasje fan it Britske FerkearsburoOffisjele webside fan English Heritage, de organisaasje dy't him ynset foar it behâld fan it Ingelske kultuergoedYnwennertallen fan alle Britske stêden út 'e folkstelling fan 2011Notes en References, op dizze sideEngland

            Հադիս Բովանդակություն Անվանում և նշանակություն | Դասակարգում | Աղբյուրներ | Նավարկման ցանկ