如何在 R 数据框中将多个字符串列的首字母转换为大写?
要将 R 数据框中多个字符串列的首字母转换为大写,我们可以按照以下步骤操作:
首先,创建一个包含字符串列的数据框。
然后,使用 dplyr 包中的 sub 函数和 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
输出
执行上述脚本后,将生成以下输出(由于随机化,此输出将在您的系统上有所不同):
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
将多个列的首字母转换为大写
使用 dplyr 包中的 sub 函数和 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
广告