How do I avoid eval and parse? The Next CEO of Stack OverflowAvoiding 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

How do I make a variable always equal to the result of some calculations?

Complex fractions

Why am I allowed to create multiple unique pointers from a single object?

Do I need to enable Dev Hub in my PROD Org?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

What was the first Unix version to run on a microcomputer?

Is it professional to write unrelated content in an almost-empty email?

How do I transpose the 1st and -1th levels of an arbitrarily nested array?

Are there any limitations on attacking while grappling?

Would a completely good Muggle be able to use a wand?

What does "Its cash flow is deeply negative" mean?

Several mode to write the symbol of a vector

How to invert MapIndexed on a ragged structure? How to construct a tree from rules?

Which tube will fit a -(700 x 25c) wheel?

WOW air has ceased operation, can I get my tickets refunded?

Inappropriate reference requests from Journal reviewers

What is "(CFMCC)" on an ILS approach chart?

How to avoid supervisors with prejudiced views?

Why do airplanes bank sharply to the right after air-to-air refueling?

Is there an analogue of projective spaces for proper schemes?

Can I run my washing machine drain line into a condensate pump so it drains better?

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Skipping indices in a product

Limits on contract work without pre-agreed price/contract (UK)



How do I avoid eval and parse?



The Next CEO of Stack OverflowAvoiding 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










11















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"), .env)
source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
eval(parse(text = paste0(environment, "$", func," <- ", func)))
cat(func, "created in", environment, "n")
)
# rm(list = functions, pos = .GlobalEnv)
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
    47 mins ago
















11















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"), .env)
source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
eval(parse(text = paste0(environment, "$", func," <- ", func)))
cat(func, "created in", environment, "n")
)
# rm(list = functions, pos = .GlobalEnv)
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
    47 mins ago














11












11








11








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"), .env)
source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
eval(parse(text = paste0(environment, "$", func," <- ", func)))
cat(func, "created in", environment, "n")
)
# rm(list = functions, pos = .GlobalEnv)
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"), .env)
source(paste0("C:/Users/JT/R/Functions/", func, ".R"))
eval(parse(text = paste0(environment, "$", func," <- ", func)))
cat(func, "created in", environment, "n")
)
# rm(list = functions, pos = .GlobalEnv)
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 16 mins ago







Josh

















asked 4 hours ago









JoshJosh

300113




300113







  • 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
    47 mins ago













  • 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
    47 mins ago








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
47 mins ago






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
47 mins ago













2 Answers
2






active

oldest

votes


















4














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
    39 mins ago












  • 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
    16 mins ago


















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
    46 mins ago











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

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









4














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
    39 mins ago












  • 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
    16 mins ago















4














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
    39 mins ago












  • 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
    16 mins ago













4












4








4







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 2 hours ago









dwwdww

15.9k32659




15.9k32659












  • 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
    39 mins ago












  • 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
    16 mins ago

















  • 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
    39 mins ago












  • 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
    16 mins ago
















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
39 mins ago






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
39 mins ago














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
16 mins ago





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
16 mins ago













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
    46 mins ago















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
    46 mins ago













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 4 hours ago









thcthc

5,37611224




5,37611224












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

    – Josh
    46 mins ago

















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

    – Josh
    46 mins ago
















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

– Josh
46 mins ago





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

– Josh
46 mins ago

















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

Are there any AGPL-style licences that require source code modifications to be public? Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Force derivative works to be publicAre there any GPL like licenses for Apple App Store?Do you violate the GPL if you provide source code that cannot be compiled?GPL - is it distribution to use libraries in an appliance loaned to customers?Distributing App for free which uses GPL'ed codeModifications of server software under GPL, with web/CLI interfaceDoes using an AGPLv3-licensed library prevent me from dual-licensing my own source code?Can I publish only select code under GPLv3 from a private project?Is there published precedent regarding the scope of covered work that uses AGPL software?If MIT licensed code links to GPL licensed code what should be the license of the resulting binary program?If I use a public API endpoint that has its source code licensed under AGPL in my app, do I need to disclose my source?

2013 GY136 Descoberta | Órbita | Referências Menu de navegação«List Of Centaurs and Scattered-Disk Objects»«List of Known Trans-Neptunian Objects»

Button changing it's text & action. Good or terrible? The 2019 Stack Overflow Developer Survey Results Are Inchanging text on user mouseoverShould certain functions be “hard to find” for powerusers to discover?Custom liking function - do I need user login?Using different checkbox style for different checkbox behaviorBest Practices: Save and Exit in Software UIInteraction with remote validated formMore efficient UI to progress the user through a complicated process?Designing a popup notice for a gameShould bulk-editing functions be hidden until a table row is selected, or is there a better solution?Is it bad practice to disable (replace) the context menu?