statquant
statquant

Reputation: 14370

How can I source a R file and store all variables from the file in a list

Hello I would like to source a R file and that all variables defined in the file be stored in a list without any other environment to be affected

# my_file.R
x = 1
y = 2
z = x + y
t = 'test'

I'd like to get something like p <- source_in_list("my_file.R")

Upvotes: 2

Views: 272

Answers (1)

Nathan Werth
Nathan Werth

Reputation: 5263

You can use the local parameter for source to save the results in an environment. Here's a function that wraps it up and converts the environment into a list:

source_in_list <- function(path) {
  e <- new.env()
  source(path, local = e)
  as.list(e)
}

Upvotes: 3

Related Questions