要将多个字符串列的第一个字母转换为data.tableR中对象中的大写,我们可以按照以下步骤操作 -
首先,创建一个data.table带有字符串列的对象。
然后,使用 sub 函数和 dplyr 包的 mutate_each 函数将字符串列中的第一个字母转换为大写。
让我们创建一个data.table对象,如下所示 -
library(data.table) Names<- sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila"," kunal"),25,replace=TRUE) Level<-sample(c("low","medium","high"),25,replace=TRUE) DT<-data.table(Names,Level) DT输出结果
执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-
Names Level 1: seema high 2: john low 3: rahul low 4: kunal medium 5: shaun medium 6: john low 7: kunal medium 8: ila high 9: sam low 10: rosy medium 11: seema medium 12: ila medium 13: kunal medium 14: sarbat high 15: shaun low 16: sarbat high 17: ila medium 18: john high 19: sarbat medium 20: rahul low 21: sam low 22: teena low 23: john high 24: john low 25: ila medium Names Level
将多列中的第一个字母转换为大写
使用 sub 函数和 dplyr 包的 mutate_each 函数将 Names 和 Level 列中的第一个字母转换为大写 -
library(data.table) Names<- sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal"),25,replace=TRUE) Level<-sample(c("low","medium","high"),25,replace=TRUE) DT<-data.table(Names,Level) library(dplyr) DT %>% mutate_each(funs(sub("(.)","\\U\\1", ., perl=TRUE)))输出结果
Names Level 1: Seema High 2: John Low 3: Rahul Low 4: Kunal Medium 5: Shaun Medium 6: John Low 7: Kunal Medium 8: Ila High 9: Sam Low 10: Rosy Medium 11: Seema Medium 12: Ila Medium 13: Kunal Medium 14: Sarbat High 15: Shaun Low 16: Sarbat High 17: Ila Medium 18: John High 19: Sarbat Medium 20: Rahul Low 21: Sam Low 22: Teena Low 23: John High 24: John Low 25: Ila Medium Names Level