How to convert first letter into capital in single column data.table object in R using dplyr?



To convert first letter into capital in single column data.table object in R, we can follow the below steps −

  • First of all, create a data.table object with string column.

  • Then, use sub function along with mutate function of dplyr package to convert first letter into capital in string column.

Example

Create the data.table object

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

library(data.table) Names<- sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal","sudha","anil","yukti","jerry","tom"),25,replace=TRUE) DT<-data.table(Names) DT

Output

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

 Names 1: teena 2: teena 3: seema 4: shaun 5: shaun 6: hidayah 7: rosy 8: kunal 9: tom 10: shaun 11: ila 12: rahul 13: sam 14: rahul 15: teena 16: jerry 17: yukti 18: rosy 19: anil 20: hidayah 21: shaun 22: seema 23: sudha 24: sam 25: anil Names

Convert first letter into Capital

Using sub function along with mutate function of dplyr package to convert first letter into capital in Names column −

library(data.table) Names<- sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal","sudha","anil","yukti","jerry","tom"),25,replace=TRUE) DT<-data.table(Names) library(dplyr) DT %>% mutate(Names=sub("(.)","\U\1",DT$Names,perl=TRUE))

Output

 Names 1: Teena 2: Teena 3: Seema 4: Shaun 5: Shaun 6: Hidayah 7: Rosy 8: Kunal 9: Tom 10: Shaun 11: Ila 12: Rahul 13: Sam 14: Rahul 15: Teena 16: Jerry 17: Yukti 18: Rosy 19: Anil 20: Hidayah 21: Shaun 22: Seema 23: Sudha 24: Sam 25: Anil Names
Updated on: 2021-11-10T06:31:27+05:30

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements