I have data.table like this:
x <- data.table(
       a = c( 1,     2),     
       b = c('foo', 'bar'))
I want to add a new column 'key_' that contains the row-by-row concatenated values of a and b separated by '_':
   a   b  key_
1: 1 foo 1_foo
2: 2 bar 2_bar
For the hard-coded case, there is a simple solution:
x[, key_ := paste0(a, '_', b)]
How could I achieve this in the more generic case when the columns to be concatenated are given as an arbitrarily long character vector?
Thanks for your help!
You can use do.call(), using .SDcols to supply the columns.
x[, key_ := do.call(paste, c(.SD, sep = "_")), .SDcols = names(x)]
.SDcols = names(x) supplies all the columns of x.  You can supply any vector of names or column numbers there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With