- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert alphabets to numbers in data.table object in R?
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
- Related Articles
- How to convert alphabets to numbers in R data frame?
- How to create pivot table with sum for data stored in data.table object in R?
- How to convert a table into matrix in R?
- How to check if a character column only contains alphabets in R data frame?
- How to convert a data frame to data.table in R?
- Indexing numbers to alphabets in JavaScript
- How to convert a character data frame to numeric data frame in R?
- How to convert an old data frame to new data frame in R?
- How to convert MANOVA data frame for two-dependent variables into a count table in R?
- How to convert data.table object into a matrix in R?
- How to convert rows in an R data frame to list?
- How to convert a list to a data frame in R?
- How to convert NaN to NA in an R data frame?
- How to convert data frame values to their rank in R?
- How to convert strings in R data frame to unique integers?

Advertisements