Search code examples
rfunctionparsingeval

How to remove this <environment: 0x00000261b409ba50> from a string evaluated and parsed in R?


Noob question here. Just want to ask how to remove this environment prompt in the console of RStudio when printing a function (originally a String) that was parsed and evaluated using parse() and eval(), respectively?

Originally, I have this string that was inserted in a list:

final = "function (x) -115.2278 + 0.6304 * x + 5e-04 * x^2 + 0 * x^3 + 0 * x^4 + 0 * x^5"

But when I use parse and eval to it, it becomes:

$Polynomial function (x) -115.2278 + 0.6304 * x + 5e-04 * x^2 + 0 * x^3 + 0 * x^4 + 0 * x^5 <environment: 0x00000261b611f2e0>

I expect the output to look like this:

$Polynomial function (x) -115.2278 + 0.6304 * x + 5e-04 * x^2 + 0 * x^3 + 0 * x^4 + 0 * x^5

I hope you can help me solve this problem. Thanks!!!


Solution

  • Use cat(paste0(deparse(your_variable), collapse="\n")

    or

    Set the function environment to globalenv

    a <- function() NULL
    print(a)
    #> function() NULL
    
    environment(a) <- new.env()
    print(a)
    #> function() NULL
    #> <environment: 0x000001ff77e5c3e8>
    
    environment(a) <- globalenv()
    print(a)
    #> function() NULL
    

    But beware of what are you doing. Setting the environment to a function could let it broken if it refers to objects in their original environment. Also it is not a well practice to evaluate arbitrary string code from external sources. See Safely evaluating arithmetic expressions in R?