How to convert alphabets to numbers in R data frame?

R ProgrammingServer Side ProgrammingProgramming

To convert alphabets to numbers in R data frame, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use mutate_each function of dplyr package along with chartr function to convert alphabets to numbers.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-sample(LETTERS[1:4],25,replace=TRUE)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-sample(LETTERS[1:4],25,replace=TRUE)
df<-data.frame(x,y,z)
df

Output

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

   x y z
1  C B D
2  D D C
3  B B D
4  D A D
5  B D C
6  C B C
7  C D C
8  B B A
9  D C D
10 D A A
11 B C B
12 C B B
13 C D B
14 C A B
15 C C C
16 A C B
17 A C B
18 B C C
19 A A B
20 B C C
21 B D A
22 B B C
23 A D B
24 A D B
25 A A C

Convert alphabets to numbers

Using mutate_each function of dplyr package along with chartr function to convert alphabets in data frame df to numbers as shown below −

x<-sample(LETTERS[1:4],25,replace=TRUE)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-sample(LETTERS[1:4],25,replace=TRUE)
df<-data.frame(x,y,z)
library(dplyr)
df %>% mutate_each(funs(chartr("ABCD","1234",.)))

Output

   x y z
1  3 2 4
2  4 4 3
3  2 2 4
4  4 1 4
5  2 4 3
6  3 2 3
7  3 4 3
8  2 2 1
9  4 3 4
10 4 1 1
11 2 3 2
12 3 2 2
13 3 4 2
14 3 1 2
15 3 3 3
16 1 3 2
17 1 3 2
18 2 3 3
19 1 1 2
20 2 3 3
21 2 4 1
22 2 2 3
23 1 4 2
24 1 4 2
25 1 1 3
raja
Updated on 15-Nov-2021 10:05:37

Advertisements