0

How can I create a data frame from the following string:

my_str <- "a=1, b=2"

In other words, how can I feed y into the data.frame or data.table functions so that it gives me the same thing as

data.frame(a=1, b=2)

Think about how you can easily pass a string of form my_str <- "y~x1+x2+x3" into a statistical model in R by simply using as.formula(my_str) and effectively remove the quotes. So I am looking for a similar solution.

Thank you!

FatihAkici
  • 4,679
  • 2
  • 31
  • 48

1 Answers1

3

I would strongly discourage you from storing code as a string in R. There are almost always better ways to write R code that don't require parsing strings.

But let's assume you have no other options. Then you can write your own parser, or use R's built in parser. The expression "a=1, b=2" on it's own doesn't make any sense in R (you can't have two "assignments" separated by a comma) so it would only make sense as parameters to a function.

If you want to wrap it in data.frame(), then you can use paste() to make the string you want and then parse() and finally eval() it to run it

my_str <- "a=1, b=2"
my_code <- paste0("data.frame(", my_str, ")")
my_expr <- parse(text=my_code)
eval(my_expr)
#   a b
# 1 1 2

But like I already mentioned eval/parse should generally be avoided.

MrFlick
  • 195,160
  • 17
  • 277
  • 295