如何在R数据框中将多个字符串列的第一个字母转换为大写?
要将多个字符串列的第一个字母转换为R数据框中的大写,我们可以按照以下步骤操作-
首先,创建一个带有字符串列的数据框。
然后,使用sub函数和dplyr包的mutate_each函数将字符串列中的第一个字母转换为大写。
示例
创建数据框
让我们创建一个数据框,如下所示-
Names<- sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal"),25,replace=TRUE) Group<--sample(c("first","second","third"),25,replace=TRUE) df<--data.frame(Names,Group) df输出结果
执行时,上述脚本生成以下内容output(thisoutputwillvaryonyoursystemduetorandomization)-
Names Group 1 sarbat third 2 sarbat first 3 shaun first 4 shaun second 5 ila second 6 sam third 7 john first 8 john third 9 sam third 10 rahul second 11 ila third 12 rahul first 13 teena second 14 john first 15 teena second 16 kunal second 17 sarbat second 18 rahul first 19 ila first 20 john third 21 john second 22 sam third 23 sam first 24 seema first 25 seema second
将多列中的第一个字母转换为大写
使用sub函数和dplyr包的mutate_each函数将Names和Group列中的第一个字母转换为大写-
Names<- sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal"),25,replace=TRUE) Group<-sample(c("first","second","third"),25,replace=TRUE) df<-data.frame(Names,Group) library(dplyr) df %>% mutate_each(funs(sub("(.)","\\U\\1", ., perl=TRUE)))输出结果
Names Group 1 Rosy First 2 Hidayah Second 3 Sam First 4 Ila Third 5 Kunal Third 6 Teena Third 7 Kunal First 8 Sam First 9 Rosy Second 10 Shaun Second 11 Sarbat Second 12 Teena Third 13 Ila First 14 Shaun Third 15 Hidayah Second 16 Sam Second 17 Rosy Third 18 Hidayah Third 19 Shaun First 20 Sam Second 21 Hidayah Third 22 Sam Second 23 John Second 24 Sam First 25 Sam Second