在data.table中的列之间逐行连接值 [英] concatenate values across columns in data.table, row by row

查看:39
本文介绍了在data.table中的列之间逐行连接值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的data.table:

I have data.table like this:

x <- data.table(
       a = c( 1,     2),     
       b = c('foo', 'bar'))

我想添加一个新列'key_',其中包含以'_'分隔的a和b的逐行连接值:

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?

感谢您的帮助!

推荐答案

您可以使用 do.call(),并使用 .SDcols 来提供列。 / p>

You can use do.call(), using .SDcols to supply the columns.

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

.SDco ls = names(x)提供 x 的所有列。您可以在此处提供任何名称或列号向量。

.SDcols = names(x) supplies all the columns of x. You can supply any vector of names or column numbers there.

这篇关于在data.table中的列之间逐行连接值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆