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

R ProgrammingServer Side ProgrammingProgramming

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

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

  • Then, use sub function to convert first letter into capital in string column.

Example

Create the data.table object

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

library(data.table)
Countries<-
sample(c("india","china","russia","croatia","uk","usa","sudan","nepal","korea","germany","iceland"),25,replace=TRUE)
DT<-data.table(Countries)
DT

Output

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

   Countries
1:  nepal
2:  india
3:  india
4:  nepal
5:  india
6:  korea
7:  germany
8:  germany
9:  sudan
10: iceland
11: india
12: india
13: nepal
14: korea
15: korea
16: nepal
17: croatia
18: nepal
19: usa
20: croatia
21: usa
22: india
23: nepal
24: germany
25: russia
Countries

Convert first letter into Capital

Using sub function to convert first letter into capital in Countries column −

library(data.table)
Countries<-
sample(c("india","china","russia","croatia","uk","usa","sudan","nepal","korea","germany","iceland"),25,replace=TRUE)
DT<-data.table(Countries)
DT$Countries_new<-sub("(.)", "\\U\\1",DT$Countries,perl=TRUE)
DT

Output

    Countries Countries_new
1:  nepal     Nepal
2:  india     India
3:  india     India
4:  nepal     Nepal
5:  india     India
6:  korea     Korea
7:  germany   Germany
8:  germany   Germany
9:  sudan     Sudan
10: iceland   Iceland
11: india     India
12: india     India
13: nepal     Nepal
14: korea     Korea
15: korea     Korea
16: nepal     Nepal
17: croatia   Croatia
18: nepal     Nepal
19: usa       Usa
20: croatia   Croatia
21: usa       Usa
22: india     India
23: nepal     Nepal
24: germany   Germany
25: russia    Russia
   Countries Countries_new
raja
Published on 15-Nov-2021 06:12:11
Advertisements