How to convert the character values in an R data frame column to lower case?

R ProgrammingServer Side ProgrammingProgramming

The character values can be stored in uppercase, lowercase, or a mixture of the two. If we have values that are either in uppercase or the mixture of lower and upper then we can convert those character values to only lowercase by using tolower function. We simply need to pass the vector or column of the data frame inside the tolower function as shown in the below examples.

Example1

Consider the below data frame −

Live Demo

> x1<-sample(LETTERS[1:4],20,replace=TRUE)
> y1<-rnorm(20)
> df1<-data.frame(x1,y1)
> df1

Output

   x1     y1
1  C  -0.1036851
2  C  -0.6176530
3  B   0.5763786
4  A   0.1943794
5  C   1.1196470
6  D  -1.4202033
7  A  -1.9147143
8  D  -1.6492836
9  B   0.2806705
10 D  -1.0246326
11 B  -0.1584948
12 A   0.8301300
13 C  -1.1100439
14 C   0.4864598
15 C   1.3461719
16 D  -2.3021691
17 D  -0.8527835
18 A  -0.0160726
19 A  -1.3944416
20 D   1.5769472

Changing the character values in x1 to lowercase −

> df1$x1<-tolower(df1$x1)
> df1

Output

   x1    y1
1  c  -0.1036851
2  c  -0.6176530
3  b   0.5763786
4  a   0.1943794
5  c   1.1196470
6  d  -1.4202033
7  a  -1.9147143
8  d  -1.6492836
9  b   0.2806705
10 d  -1.0246326
11 b  -0.1584948
12 a   0.8301300
13 c  -1.1100439
14 c   0.4864598
15 c   1.3461719
16 d  -2.3021691
17 d  -0.8527835
18 a  -0.0160726
19 a  -1.3944416
20 d   1.5769472

Example2

Live Demo

> x2<-sample(LETTERS[1:10],20,replace=TRUE)
> y2<-rpois(20,5)
> df2<-data.frame(x2,y2)
> df2

Output

   x2 y2
1  G  4
2  D  3
3  G  2
4  E  3
5  B  6
6  I  2
7  A  8
8  F  6
9  A  7
10 F  5
11 C  10
12 G  5
13 I  4
14 H  7
15 F  4
16 A  3
17 J  3
18 I  3
19 D  6
20 F  8

Changing the character values in x2 to lowercase −

> df2$x2<-tolower(df2$x2)
> df2

Output

   x2 y2
1  g  4
2  d  3
3  g  2
4  e  3
5  b  6
6  i  2
7  a  8
8  f  6
9  a  7
10 f  5
11 c  10
12 g  5
13 i  4
14 h  7
15 f  4
16 a  3
17 j  3
18 i  3
19 d  6
20 f  8

Example3

Live Demo

> x3<-sample(LETTERS[1:2],20,replace=TRUE)
> y3<-runif(20,2,5)
> df3<-data.frame(x3,y3)
> df3

Output

   x3   y3
1  A  2.144779
2  A  4.020497
3  A  4.152795
4  A  4.579962
5  A  4.151587
6  B  3.668675
7  B  3.918459
8  B  2.326660
9  B  4.826448
10 A  4.159623
11 B  4.966475
12 B  4.159850
13 B  4.478584
14 A  2.585765
15 B  3.661653
16 B  2.836051
17 B  3.947854
18 B  3.650995
19 A  3.333785
20 A  2.147321

Changing the character values in x3 to lowercase −

> df3$x3<-tolower(df3$x3)
> df3

Output

   x3  y3
1  a  2.144779
2  a  4.020497
3  a  4.152795
4  a  4.579962
5  a  4.151587
6  b  3.668675
7  b  3.918459
8  b  2.326660
9  b  4.826448
10 a  4.159623
11 b  4.966475
12 b  4.159850
13 b  4.478584
14 a  2.585765
15 b  3.661653
16 b  2.836051
17 b  3.947854
18 b  3.650995
19 a  3.333785
20 a  2.147321
raja
Published on 04-Mar-2021 08:11:39
Advertisements