0

Is there a function like parse_R in the example below that parses a string into the R object it represents? Or more generally, a function that returns whatever the chunk of R code in the string would have returned if you ran it in the current R environment?

> string <- "c(1,2,3,4)"
> vec <- parse_R(string)
> class(vec)
[1] "numeric"
> print(vec)
[1]  1 2 3 4

Maybe eval can do this? I haven't been able to really figure out how though.

andrew
  • 2,524
  • 2
  • 24
  • 36
  • 1
    You're looking for `eval(parse(text = "c(1,2,3,4)"))`, but if people see you using that in actual code you will probably get some criticism. It is frowned upon. – joran Aug 21 '14 at 21:28
  • Thanks! Why specifically is it frowned upon? – andrew Aug 21 '14 at 21:29
  • 1
    See [What specifically are the dangers of eval(parse(...))](http://stackoverflow.com/q/13649979/903061) – Gregor Thomas Aug 21 '14 at 21:36
  • 1
    See `library(fortunes); fortune(106); fortune('106')`. Like anything else, there is a time and place for it, but it's something (like `assign` and `get`) that inexperienced R programmers turn too far too quickly, rather than figuring out better ways doing things within the usual tools in R. – joran Aug 21 '14 at 21:36
  • @joran, in this particular case, aren't they more likely looking for `dget(textConnection(string))`? That makes it less of a duplicate of the presently identified duplicate. Although `dget` is essentially `eval(parse(text = .))` :-) – A5C1D2H2I1M1N2O1R2T1 Aug 22 '14 at 16:51

0 Answers0