How to combine two columns of a data.table object in R?


A data.table object is almost same as a data frame. To combine two columns of a data.table object, we can use paste0 function. For example, if we have a data frame defined as DT that contains two columns named as x and y then we can combine them using the below command.

DT[,xy:=paste0(x,y)]

Example

Loading data.table package.

> library(data.table)

Consider the below data.table object.

Example

> x<-1:20
> y<-letters[1:20]
> dt1<-data.table(x,y)
> dt1

Output

x y
1: 1 a
2: 2 b
3: 3 c
4: 4 d
5: 5 e
6: 6 f
7: 7 g
8: 8 h
9: 9 i
10: 10 j
11: 11 k
12: 12 l
13: 13 m
14: 14 n
15: 15 o
16: 16 p
17: 17 q
18: 18 r
19: 19 s
20: 20 t

Combining columns x and y.

Example

> dt1[,xy:=paste0(x,y)]
> dt1

Output

x y xy
1: 1 a 1a
2: 2 b 2b
3: 3 c 3c
4: 4 d 4d
5: 5 e 5e
6: 6 f 6f
7: 7 g 7g
8: 8 h 8h
9: 9 i 9i
10: 10 j 10j
11: 11 k 11k
12: 12 l 12l
13: 13 m 13m
14: 14 n 14n
15: 15 o 15o
16: 16 p 16p
17: 17 q 17q
18: 18 r 18r
19: 19 s 19s
20: 20 t 20t

Let’s have a look at another example.

Example

> Group<-sample(c("G1","G2","G3","G4"),20,replace=TRUE)
> Class<-sample(c("I","II","III"),20,replace=TRUE)
> dt2<-data.table(Group,Class)
> dt2

Output

Group Class
1: G3 I
2: G1 II
3: G3 II
4: G4 I
5: G1 I
6: G3 II
7: G1 III
8: G3 I
9: G2 III
10: G3 II
11: G3 I
12: G2 II
13: G2 II
14: G3 III
15: G4 III
16: G4 I
17: G2 II
18: G4 II
19: G1 III
20: G4 II

Combining columns Group and Class.

Example

> dt2[,GC:=paste0(Group,Class)]
> dt2

Output

Group Class GC
1: G3 I G3I
2: G1 II G1II
3: G3 II G3II
4: G4 I G4I
5: G1 I G1I
6: G3 II G3II
7: G1 III G1III
8: G3 I G3I
9: G2 III G2III
10: G3 II G3II
11: G3 I G3I
12: G2 II G2II
13: G2 II G2II
14: G3 III G3III
15: G4 III G4III
16: G4 I G4I
17: G2 II G2II
18: G4 II G4II
19: G1 III G1III
20: G4 II G4II

Updated on: 07-Nov-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements