Home > Net >  Convert list of strings to list of expressions?
Convert list of strings to list of expressions?

Time:08-11

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

CodePudding user response:

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
  •  Tags:  
  • r
  • Related