如何在R中使用dplyr将单列data.table对象中的首字母转换为大写?
要在R中将单列data.table对象中的首字母转换为大写,我们可以按照以下步骤操作:
首先,创建一个包含字符串列的data.table对象。
然后,使用dplyr包中的mutate函数和sub函数将字符串列中的首字母转换为大写。
示例
创建data.table对象
让我们创建一个如下所示的data.table对象:
library(data.table) Names<- sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal","sudha","anil","yukti","jerry","tom"),25,replace=TRUE) DT<-data.table(Names) DT
输出
执行上述脚本后,将生成以下输出(由于随机化,此输出在您的系统上可能会有所不同):
Names 1: teena 2: teena 3: seema 4: shaun 5: shaun 6: hidayah 7: rosy 8: kunal 9: tom 10: shaun 11: ila 12: rahul 13: sam 14: rahul 15: teena 16: jerry 17: yukti 18: rosy 19: anil 20: hidayah 21: shaun 22: seema 23: sudha 24: sam 25: anil Names
将首字母转换为大写
使用dplyr包中的mutate函数和sub函数将Names列中的首字母转换为大写:
library(data.table) Names<- sample(c("rahul","rosy","hidayah","seema","john","sarbat","shaun","sam","teena","ila","kunal","sudha","anil","yukti","jerry","tom"),25,replace=TRUE) DT<-data.table(Names) library(dplyr) DT %>% mutate(Names=sub("(.)","\U\1",DT$Names,perl=TRUE))
输出
Names 1: Teena 2: Teena 3: Seema 4: Shaun 5: Shaun 6: Hidayah 7: Rosy 8: Kunal 9: Tom 10: Shaun 11: Ila 12: Rahul 13: Sam 14: Rahul 15: Teena 16: Jerry 17: Yukti 18: Rosy 19: Anil 20: Hidayah 21: Shaun 22: Seema 23: Sudha 24: Sam 25: Anil Names
广告