Convert First Letter of Multiple String Columns to Capital in Data Table Object in R



To convert first letter of multiple string columns into capital in data.table object in R, we can follow the below steps −

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

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

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"),25,replace=TRUE)
Level<-sample(c("low","medium","high"),25,replace=TRUE)
DT<-data.table(Names,Level)
DT

Output

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

    Names  Level
1:  seema  high
2:  john   low
3:  rahul  low
4:  kunal  medium
5:  shaun  medium
6:  john   low
7:  kunal  medium
8:  ila    high
9:  sam    low
10: rosy   medium
11: seema  medium
12: ila    medium
13: kunal  medium
14: sarbat high
15: shaun  low
16: sarbat high
17: ila    medium
18: john   high
19: sarbat medium
20: rahul  low
21: sam    low
22: teena  low
23: john   high
24: john   low
25: ila    medium
    Names Level

Convert first letter into capital in multiple columns

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

library(data.table)
Names<-
sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal"),25,replace=TRUE)
Level<-sample(c("low","medium","high"),25,replace=TRUE)
DT<-data.table(Names,Level)
library(dplyr)
DT %>% mutate_each(funs(sub("(.)","\U\1", ., perl=TRUE)))

Output

    Names   Level
1:  Seema   High
2:  John    Low
3:  Rahul   Low
4:  Kunal   Medium
5:  Shaun   Medium
6:  John    Low
7:  Kunal   Medium
8:  Ila     High
9:  Sam     Low
10: Rosy    Medium
11: Seema   Medium
12: Ila     Medium
13: Kunal   Medium
14: Sarbat  High
15: Shaun   Low
16: Sarbat  High
17: Ila     Medium
18: John    High
19: Sarbat  Medium
20: Rahul   Low
21: Sam     Low
22: Teena   Low
23: John    High
24: John    Low
25: Ila     Medium
   Names    Level
Updated on: 2021-11-11T07:17:45+05:30

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements