eval() within a function
essai <- function() {
mx <- 10
eval(parse(text="k=20"), envir= environment())
print(k)
}
essai()
# by default the environment used is .GlobalEnv
# mx is not known in this environment
essai <- function() {
mx <- 10
eval(parse(text="k=mx"))
print(k)
}
essai()
essai <- function() {
mx <- 10
eval(parse(text="k=mx"), envir= .GlobalEnv)
print(k)
}
essai()
# Here I force mx to be defined in .GlobalEnv
essai <- function() {
mx <<- 10
eval(parse(text="k=mx"), envir= .GlobalEnv)
print(k)
}
essai()
# environment() is the environment of the function
essai <- function() {
mx <- 10
eval(parse(text="k=mx"), envir= environment())
print(k)
}
essai()
essai <- function() {
env <- new.env(parent = environment())
mx <- 10
eval(parse(text="k=mx"), envir= env)
print(k)
}
essai()
mx <- 10
eval(parse(text="k=20"), envir= environment())
print(k)
}
essai()
# by default the environment used is .GlobalEnv
# mx is not known in this environment
essai <- function() {
mx <- 10
eval(parse(text="k=mx"))
print(k)
}
essai()
essai <- function() {
mx <- 10
eval(parse(text="k=mx"), envir= .GlobalEnv)
print(k)
}
essai()
# Here I force mx to be defined in .GlobalEnv
essai <- function() {
mx <<- 10
eval(parse(text="k=mx"), envir= .GlobalEnv)
print(k)
}
essai()
# environment() is the environment of the function
essai <- function() {
mx <- 10
eval(parse(text="k=mx"), envir= environment())
print(k)
}
essai()
essai <- function() {
env <- new.env(parent = environment())
mx <- 10
eval(parse(text="k=mx"), envir= env)
print(k)
}
essai()
Commentaires
Enregistrer un commentaire