简体   繁体   中英

Passing a string as a column name in data.table

I am trying to create a function to eliminate repetition in my code but am having issues using the eval function to pass a string as a column name using data.table. Sample code:

sample = data.table(a = 1:10,b=1:10)
sample

example = 'test_string'

working = sample[,.(test_string=a+b)]
working

notworking = sample[,.(eval(example)=a+b)]
notworking1 = sample[,eval(as.name(example):=a+b)]
notworking2 = sample[,eval(example):=a+b]

Any advice would help

We need to just wrap it in brackets for evaluating it

sample[, (example) := a + b]

-output

> sample
        a     b test_string
    <int> <int>       <int>
 1:     1     1           2
 2:     2     2           4
 3:     3     3           6
 4:     4     4           8
 5:     5     5          10
 6:     6     6          12
 7:     7     7          14
 8:     8     8          16
 9:     9     9          18
10:    10    10          20

If we don't need to create a column in the original data ( := ), use setNames

sample[, setNames(.(a + b), example)]
     test_string
          <int>
 1:           2
 2:           4
 3:           6
 4:           8
 5:          10
 6:          12
 7:          14
 8:          16
 9:          18
10:          20

or setnames

setnames(sample[, .(a + b)], example)[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM