Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)[]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading