Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert list of strings to list of expressions?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading