How to convert first letter into capital in R data frame column?


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

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

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

Example

Create the data frame

Let’s create a data frame as shown below −

Names<-
sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal"),25,replace=TRUE)
df<-data.frame(Names)
df

Output

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

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

Convert first letter into Capital

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

Names<-
sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal"),25,replace=TRUE)
df<-data.frame(Names)
df$New_Names<-sub("(.)", "\U\1",df$Names,perl=TRUE)
df

Output

   Names  New_Names
1  rahul   Rahul
2  teena   Teena
3  hidayah Hidayah
4  kunal   Kunal
5  shaun   Shaun
6  sarbat  Sarbat
7  teena   Teena
8  john    John
9  ila     Ila
10 ila     Ila
11 rahul   Rahul
12 ila     Ila
13 rahul   Rahul
14 sarbat  Sarbat
15 seema   Seema
16 seema   Seema
17 teena   Teena
18 shaun   Shaun
19 hidayah Hidayah
20 sarbat  Sarbat
21 sarbat  Sarbat
22 teena   Teena
23 seema   Seema
24 ila     Ila
25 sam     Sam

Updated on: 10-Nov-2021

934 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements