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