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()

Commentaires

Posts les plus consultés de ce blog

Standard error from Hessian Matrix... what can be done when problem occurs

Multivariable analysis and correlation of iconography

Install treemix in ubuntu 20.04