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


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

  • First of all, create a data frame 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 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  teena
2  shaun
3  kunal
4  rosy
5  sam
6  teena
7  hidayah
8  teena
9  sarbat
10 kunal
11 sam
12 teena
13 kunal
14 rosy
15 hidayah
16 sam
17 shaun
18 seema
19 rosy
20 john
21 seema
22 ila
23 john
24 shaun
25 rosy

Convert first letter into Capital

Using sub function along with mutate function of dplyr package 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)
library(dplyr)
df %>% mutate(Names=sub("(.)","\U\1",df$Names,perl=TRUE))

Output

   Names
1  John
2  Hidayah
3  Teena
4  Sam
5  John
6  Rosy
7  Rahul
8  Teena
9  Sarbat
10 Kunal
11 Kunal
12 Rahul
13 Rosy
14 Sarbat
15 Shaun
16 Kunal
17 Teena
18 Hidayah
19 Sam
20 Sam
21 Sarbat
22 Seema
23 Rahul
24 Shaun
25 John

Updated on: 09-Nov-2021

476 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements