如何将R数据框列中的第一个字母转换为大写?
要将R数据框列中的第一个字母转换为大写,我们可以按照以下步骤操作-
首先,创建一个带有字符串列的数据框。
然后,使用sub函数将字符串列中的第一个字母转换为大写。
示例
创建数据框
让我们创建一个数据框,如下所示-
Names<- sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal"),25,replace=TRUE) df<-data.frame(Names) df输出结果
执行时,上述脚本生成以下内容output(thisoutputwillvaryonyoursystemduetorandomization)-
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
将第一个字母转换为大写
使用sub函数将Names列中的第一个字母转换为大写-
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输出结果
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