How to convert alphabets to numbers in data.table object in R?

R ProgrammingServer Side ProgrammingProgramming

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

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

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

Example

Create the data.table object

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

library(data.table)
v1<-sample(LETTERS[1:5],25,replace=TRUE)
v2<-sample(LETTERS[1:5],25,replace=TRUE)
v3<-sample(LETTERS[1:5],25,replace=TRUE)
DT<-data.table(v1,v2,v3)
DT

Output

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

    v1 v2 v3
1:  E  C  B
2:  A  C  B
3:  C  A  D
4:  A  E  D
5:  D  A  A
6:  E  B  E
7:  D  A  D
8:  A  B  A
9:  D  D  B
10: E  B  E
11: C  C  D
12: E  C  C
13: B  D  A
14: C  A  C
15: C  B  D
16: B  C  B
17: B  B  E
18: D  D  C
19: A  C  A
20: C  E  D
21: D  A  D
22: E  D  A
23: B  A  C
24: E  D  E
25: A  B  D
   v1 v2  v3

Convert alphabets to numbers

Using mutate_each function of dplyr package along with chartr function to convert alphabets in data.table object DT to numbers as shown below −

library(data.table)
v1<-sample(LETTERS[1:5],25,replace=TRUE)
v2<-sample(LETTERS[1:5],25,replace=TRUE)
v3<-sample(LETTERS[1:5],25,replace=TRUE)
DT<-data.table(v1,v2,v3)
library(dplyr)
DT %>% mutate_each(funs(chartr("ABCDE","12345",.)))

Output

    v1 v2 v3
1:  5  3  2
2:  1  3  2
3:  3  1  4
4:  1  5  4
5:  4  1  1
6:  5  2  5
7:  4  1  4
8:  1  2  1
9:  4  4  2
10: 5  2  5
11: 3  3  4
12: 5  3  3
13: 2  4  1
14: 3  1  3
15: 3  2  4
16: 2  3  2
17: 2  2  5
18: 4  4  3
19: 1  3  1
20: 3  5  4
21: 4  1  4
22: 5  4  1
23: 2  1  3
24: 5  4  5
25: 1  2  4
   v1 v2  v3
raja
Published on 08-Nov-2021 10:51:39

Advertisements