How do I avoid eval and parse?

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)

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.

Tags:

Eval

R