Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate values across columns in data.table, row by row

Tags:

r

data.table

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!

like image 389
Steffen J. Avatar asked Sep 18 '17 20:09

Steffen J.


1 Answers

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.

like image 166
Rich Scriven Avatar answered Oct 23 '22 22:10

Rich Scriven