qdread
qdread

Reputation: 3973

Define variables using eval() within lapply() in R

First I define

args <- c("x=5", "y=10")

The following has expected behavior in R (creates variables x and y in global environment)

for (i in 1:length(args)) {
  eval(parse(text=args[[i]]))
}

However the following just returns an unnamed list.

lapply(args, function(a) eval(parse(text = a)))

Can you use an apply function to create the variables instead of a loop?

Upvotes: 2

Views: 235

Answers (1)

akrun
akrun

Reputation: 887501

We create a named list and then with list2env

list2env(setNames(lapply(args, function(a) eval(parse(text = a))), 
            sub("\\=.*", "", args)), envir = .GlobalEnv)
x
#[1] 5
y
#[1] 10

Upvotes: 3

Related Questions