How to separate two values in single column in R data frame?

R ProgrammingServer Side ProgrammingProgramming

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

  • First of all, create a data frame.

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

Example

Create the data frame

Let’s create a data frame as shown below −

df<-
data.frame(x=sample(c("1,2","2,3","3,4","4,5","5,6","6,7","7,8","8,9","9,10"),25,replace=TRUE))
df

Output

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

    x
1  9,10
2  6,7
3  7,8
4  3,4
5  8,9
6  8,9
7  1,2
8  2,3
9  2,3
10 4,5
11 2,3
12 4,5
13 6,7
14 9,10
15 9,10
16 7,8
17 1,2
18 4,5
19 5,6
20 3,4
21 1,2
22 9,10
23 4,5
24 1,2
25 2,3

Separate values in column

Using separate function from tidyr package to separate the values in column x of data frame df −

df<-
data.frame(x=sample(c("1,2","2,3","3,4","4,5","5,6","6,7","7,8","8,9","9,10"),25,replace= TRUE))
library(tidyr)
df %>% separate(x,c("First","Last"),sep=",")

Output

  First Last
1  7    8
2  7    8
3  7    8
4  2    3
5  2    3
6  2    3
7  4    5
8  6    7
9  2    3
10 3    4
11 9   10
12 8    9
13 7    8
14 6    7
15 3    4
16 3    4
17 2    3
18 7    8
19 9   10
20 5    6
21 9   10
22 4    5
23 5    6
24 6    7
25 6    7
raja
Updated on 10-Nov-2021 06:40:30

Advertisements