Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut for evaluating strings in data.table assignments

Tags:

r

data.table

eval

Wrangling data with data.table's, I find myself writing lines like this third line a lot:

DT = data.table(a = 1:10)
name = 'a'
DT[,eval(parse(text=sprintf('%s_plus_one := %s + 1',name,name)))]

which I had hoped to reduce to

DT[,s('%s_plus_one := %s + 1',name,name)]

using a function like:

# s is *very* short for substitute and evalute
s <- function(...)
    eval(parse(text=sprintf(...)))

but then I get this error:

> DT[,s('%s_plus_one := %s + 1',name,name)]
    Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").

I know I can do this:

# sp is short for substitute and parse
sp <- function(...)
    parse(text=sprintf(...))

DT[,eval(sp('%s_plus_one := %s + 1',name,name))]
DT
#>      a a_plus_one
#>  1:  1          2
#>  2:  2          3
#>  3:  3          4
#>  4:  4          5

but building strings to be evaluated in a data.table assignment is so common, that I'd hoped minimize typing as much as possible.

like image 807
Jthorpe Avatar asked May 31 '26 19:05

Jthorpe


1 Answers

Much of the time there shouldn't even be a need to go into the world of eval(parse()). I.e., for this example, put the name in parentheses on the left-hand side and use get on the right-hand side:

DT[, (paste0(name,"_plus_one")) := get(name) + 1]

DT
#     a a_plus_one
# 1:  1          2
# 2:  2          3
# 3:  3          4
# 4:  4          5
# 5:  5          6
# 6:  6          7
# 7:  7          8
# 8:  8          9
# 9:  9         10
#10: 10         11
like image 81
thelatemail Avatar answered Jun 02 '26 09:06

thelatemail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!