0

How to compress a function from eval(parse(text='5+5')) to eval2('5+5'), so as not to write 3 words each time instead of one?

I use this construction very often, I need to compress it.

UPD: Complicating the case, because packing eval into a function does not work, for example, with data.table. I would like eval(parse(text=)) to turn into eval() in this case:

dt <- data.table(a = c(1, 1, 1, 1), foo_col = c('a', 'b', 'X', 'asd')) cur_col <- 'foo_col2' dt[, eval(parse(text=glue::glue('{cur_col} := c(3, 3, 3, 3)')))] 

P.S.: The design dt[, (cur_col) := c(3, 3, 3, 3)] does not suit. On it, data.table in an exotic case complains about unnecessary copying.

But it does not complain when using eval(parse(text=

In addition, I often use this construction in principle, so I want to bring it to mind.

7
  • fortunes::fortune("parse") not work Commented Jul 7, 2022 at 17:27
  • 2
    What problem are you actually trying to solve? Using this eval/parse construct is really not how R wants to be used. Generally it should be avoided. Commented Jul 7, 2022 at 17:52
  • So this problem is specific to data.table? Because that has different rules than normal R syntax. Commented Jul 7, 2022 at 17:54
  • To add to my first comment, from Programming on data.table, "Although ths provides unlimited flexibility with relatively low complexity, use of eval(parse(...)) should be avoided." Commented Jul 7, 2022 at 18:00
  • OK, you might be right, try fortunes::fortune(106) instead. Commented Jul 7, 2022 at 18:00

1 Answer 1

1

Just by writing a wrapper function around these eval and parse

eval2 <- function(txt) { eval(parse(text = txt)) } eval2('5 + 5') #> [1] 10 eval(parse(text = '5 + 5')) #> [1] 10 

Created on 2022-07-07 by the reprex package (v2.0.1)

Sign up to request clarification or add additional context in comments.

2 Comments

I made a case on which it will not work
@Avraam in that case use set(dt, j=cur_col, value=3) You did not say you wanted to use data.table The answer given here is for base R

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.