I had a similar issue but had many columns, and didn't want to type them each manually.
New version
(based on comment from @mnel)
dt[, new:=do.call(paste0,.SD), .SDcols=-1]
This is roughly twice as fast as the old version, and seems to sidestep the quirks. Note the use of .SDcols
to identify the columns to use in paste0
. The -1
uses all columns but the first, since the OP wanted to paste columns A and B but not L.
If you would like to use a different separator:
dt[ , new := do.call(paste, c(.SD, sep = ":"))]
Old version
You can use .SD
and by
to handle multiple columns:
dt[,new:=paste0(.SD,collapse=""),by=seq_along(L)]
I added seq_along
in case L was not unique. (You can check this using dt<-data.table(L=c(1:4,4),A=letters[7:11],B=letters[12:16])
).
Also, in my actual instance for some reason I had to use t(.SD)
in the paste0
part. There may be other similar quirks.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…