Reputation: 125
In R, I have a list of strings that I would like to convert to a list of expressions. Is this at all possible? I have tried a few functions like eval() or parse() but they don't seem to do the trick. Here is an example below.
## What my list currently looks like
current = list(
"A = c(0,1)",
"B = c(0,2)"
)
## What I would like it to be
ideal = list(
A = c(0,1),
B = c(0,2)
)
> print(current)
[[1]]
[1] "A = c(0,1)"
[[2]]
[1] "B = c(0,2)"
> print(ideal)
$A
[1] 0.0 1.0
$B
[1] 0.0 2.0
Upvotes: 2
Views: 187
Reputation: 6529
You could solve your problem as follow:
eval(parse(text = sprintf("list(%s)", toString(current))))
$A
[1] 0 1
$B
[1] 0 2
Upvotes: 1
Reputation: 887951
We could paste
and do an eval
eval(parse(text = paste("list(", toString(unlist(current)), ")")))
-output
$A
[1] 0 1
$B
[1] 0 2
Or get the dput
and then use eval/parse
eval(parse(text = gsub('"', '', capture.output(dput(current)))))
$A
[1] 0 1
$B
[1] 0 2
Upvotes: 1