This question is a follow up to paste two data.table columns, and I'll therefore use the same example:
Start with a data.table
:
dt <- data.table(L=1:5,A=letters[7:11],B=letters[12:16])
L A B
1: 1 g l
2: 2 h m
3: 3 i n
4: 4 j o
5: 5 k p
I would like to create a new column that is the combination of two columns, dt$A
and dt$B
specifically.
dt[, new := paste0(A, B)]
dt
L A B new
1: 1 g l gl
2: 2 h m hm
3: 3 i n in
4: 4 j o jo
5: 5 k p kp
As I'm using new
as a sort of ID column, and would prefer some human-readability, I want to use a character to separate the contents of dt$A
and dt$B
, so:
dt[, new := paste0(A, B, collapse = ".")]
But this alters the behaviour unexpectedly:
dt
L A B new
1: 1 g l gl.hm.in.jo.kp
2: 2 h m gl.hm.in.jo.kp
3: 3 i n gl.hm.in.jo.kp
4: 4 j o gl.hm.in.jo.kp
5: 5 k p gl.hm.in.jo.kp