简体   繁体   English

在data.table中逐行连接各列的值

[英]concatenate values across columns in data.table, row by row

I have data.table like this: 我有data.table像这样:

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 '_': 我想添加一个新列'key_',其中包含由'_'分隔的a和b的逐行连接值:

   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. 您可以使用do.call() ,使用.SDcols来提供列。

x[, key_ := do.call(paste, c(.SD, sep = "_")), .SDcols = names(x)]

.SDcols = names(x) supplies all the columns of x . .SDcols = names(x)供给的所有列x You can supply any vector of names or column numbers there. 您可以在那里提供任何名称或列号的向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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