How do I avoid eval and parse?
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
add a comment |
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
1
Just discovered thateval(parse(text = paste0("detach(", environment, ")")))
can be replaced withdetach(environment, character.only = T)
. The question about improvingeval(parse(text = paste0("attach(", environment, ")")))
remains.
– Josh
1 hour ago
add a comment |
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
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
r eval
edited 52 mins ago
Josh
asked 5 hours ago
JoshJosh
300113
300113
1
Just discovered thateval(parse(text = paste0("detach(", environment, ")")))
can be replaced withdetach(environment, character.only = T)
. The question about improvingeval(parse(text = paste0("attach(", environment, ")")))
remains.
– Josh
1 hour ago
add a comment |
1
Just discovered thateval(parse(text = paste0("detach(", environment, ")")))
can be replaced withdetach(environment, character.only = T)
. The question about improvingeval(parse(text = paste0("attach(", environment, ")")))
remains.
– Josh
1 hour 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
1 hour 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
1 hour ago
add a comment |
2 Answers
2
active
oldest
votes
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)
Thank you, I missed that aspect ofsource()
. However, if I change that line of code tosource(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment)
I get the errorError 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 fromenvironment
toenv
?
– Josh
1 hour ago
You should create an environment to save into. For example as I demonstrated withenv = 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 useassign(environment, new.env())
– dww
51 mins ago
add a comment |
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.
I agree. I eventually need to learn how to do this.
– Josh
1 hour ago
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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)
Thank you, I missed that aspect ofsource()
. However, if I change that line of code tosource(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment)
I get the errorError 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 fromenvironment
toenv
?
– Josh
1 hour ago
You should create an environment to save into. For example as I demonstrated withenv = 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 useassign(environment, new.env())
– dww
51 mins ago
add a comment |
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)
Thank you, I missed that aspect ofsource()
. However, if I change that line of code tosource(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment)
I get the errorError 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 fromenvironment
toenv
?
– Josh
1 hour ago
You should create an environment to save into. For example as I demonstrated withenv = 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 useassign(environment, new.env())
– dww
51 mins ago
add a comment |
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)
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)
answered 3 hours ago
dwwdww
15.9k32659
15.9k32659
Thank you, I missed that aspect ofsource()
. However, if I change that line of code tosource(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment)
I get the errorError 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 fromenvironment
toenv
?
– Josh
1 hour ago
You should create an environment to save into. For example as I demonstrated withenv = 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 useassign(environment, new.env())
– dww
51 mins ago
add a comment |
Thank you, I missed that aspect ofsource()
. However, if I change that line of code tosource(paste0("C:/Users/JT/R/Functions/", func, ".R"), local = environment)
I get the errorError 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 fromenvironment
toenv
?
– Josh
1 hour ago
You should create an environment to save into. For example as I demonstrated withenv = 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 useassign(environment, new.env())
– dww
51 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
1 hour 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
1 hour 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
51 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
51 mins ago
add a comment |
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.
I agree. I eventually need to learn how to do this.
– Josh
1 hour ago
add a comment |
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.
I agree. I eventually need to learn how to do this.
– Josh
1 hour ago
add a comment |
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.
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.
answered 4 hours ago
thcthc
5,37611224
5,37611224
I agree. I eventually need to learn how to do this.
– Josh
1 hour ago
add a comment |
I agree. I eventually need to learn how to do this.
– Josh
1 hour ago
I agree. I eventually need to learn how to do this.
– Josh
1 hour ago
I agree. I eventually need to learn how to do this.
– Josh
1 hour ago
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
1
Just discovered that
eval(parse(text = paste0("detach(", environment, ")")))
can be replaced withdetach(environment, character.only = T)
. The question about improvingeval(parse(text = paste0("attach(", environment, ")")))
remains.– Josh
1 hour ago