# How to separate two values in single column in data.table object in R?

To separate two values in single column in data.table object in R, we can follow the below steps −

• First of all, create a data.table object.

• Then, use separate function from tidyr package to separate the values in single column.

## Example

#### Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
DT<-
data.table(x=sample(c("A,B","B,C","C,D","D,E","E,F","F,G","G,H"),25,replace=TRUE))
DT

## Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

    x
1:  C,D
2:  C,D
3:  C,D
4:  A,B
5:  F,G
6:  A,B
7:  C,D
8:  G,H
9:  B,C
10: C,D
11: G,H
12: G,H
13: G,H
14: C,D
15: F,G
16: G,H
17: C,D
18: C,D
19: F,G
20: G,H
21: E,F
22: A,B
23: G,H
24: D,E
25: F,G
x

Separate values in column

Using separate function from tidyr package to separate the values in column x of data.table object DT −

library(data.table)
DT<-
data.table(x=sample(c("A,B","B,C","C,D","D,E","E,F","F,G","G,H"),25,replace=TRUE))
library(tidyr)
DT %>% separate(x,c("Group1","Group2"),sep=",")

## Output

  Group1 Group2
1:  C     D
2:  C     D
3:  C     D
4:  A     B
5:  F     G
6:  A     B
7:  C     D
8:  G     H
9:  B     C
10: C     D
11: G     H
12: G     H
13: G     H
14: C     D
15: F     G
16: G     H
17: C     D
18: C     D
19: F     G
20: G     H
21: E     F
22: A     B
23: G     H
24: D     E
25: F     G
Group1 Group2