How to replace space between two words with underscore in an R data frame column?

R ProgrammingServer Side ProgrammingProgramming

To replace space between two words with underscore in an R data frame column, we can use gsub function. For example, if we have a data frame called df that contains character column x having two words having a single space between them then we can replace that space using the command df$x<-gsub(" ", "_",df$x)

Example

Consider the below data frame −

 Live Demo

x1<-sample(c("id 1","id 2","id 3","id 4"),20,replace=TRUE)
x2<-rpois(20,5)
df1<-data.frame(x1,x2)
df1

Output

    x1   x2
1 id 4   6
2 id 4   5
3 id 1   6
4 id 3   8
5 id 4  12
6 id 4   8
7 id 3   2
8 id 3   5
9 id 4   8
10 id 1  1
11 id 3  4
12 id 3  5
13 id 2  3
14 id 1  2
15 id 3  5
16 id 1  8
17 id 4  8
18 id 3  5
19 id 2  2
20 id 3  4

Replacing space between id and the number in column x1 with underscore −

Example

df1$x1<-gsub(" ", "_", df1$x1)
df1

Output

    x1   x2
1 id_4   6
2 id_4   5
3 id_1   6
4 id_3   8
5 id_4  12
6 id_4   8
7 id_3   2
8 id_3   5
9 id_4   8
10 id_1  1
11 id_3  4
12 id_3  5
13 id_2  3
14 id_1  2
15 id_3  5
16 id_1  8
17 id_4  8
18 id_3  5
19 id_2  2
20 id_3  4

Example

 Live Demo

y1<-sample(c("class 1","class 2","class 3"),20,replace=TRUE)
y2<-rnorm(20)
df2<-data.frame(y1,y2)
df2

Output

     y1         y2
1  class 1   0.62986928
2  class 2   1.65731515
3  class 3  -1.13406383
4  class 1  -0.35842133
5  class 1   0.58141698
6  class 3  -0.18424254
7  class 3  -1.05955455
8  class 2  -0.80841041
9  class 3   1.05838028
10 class 2  -1.06141883
11 class 3  -0.54195571
12 class 3  -0.18038280
13 class 2   0.75236011
14 class 2  -0.55374067
15 class 1   0.38737080
16 class 3   0.35892853
17 class 2  -0.44576804
18 class 1   0.62543133
19 class 2  -0.05862987
20 class 1  -0.01508226

Replacing space between id and the number in column y1 with underscore −

Example

df2$y1<-gsub(" ", "_",df2$y1)
df2

Output

      y1        y2
1  class_1   0.62986928
2  class_2   1.65731515
3  class_3  -1.13406383
4  class_1  -0.35842133
5  class_1   0.58141698
6  class_3  -0.18424254
7  class_3  -1.05955455
8  class_2  -0.80841041
9  class_3   1.05838028
10 class_2  -1.06141883
11 class_3  -0.54195571
12 class_3  -0.18038280
13 class_2   0.75236011
14 class_2  -0.55374067
15 class_1   0.38737080
16 class_3   0.35892853
17 class_2  -0.44576804
18 class_1   0.62543133
19 class_2  -0.05862987
20 class_1  -0.01508226
raja
Published on 17-Mar-2021 07:15:14
Advertisements