如何将 R 中 data.table 对象列开头的字母转换为大写字母?
在 R 中的 data.table 对象列中将首字母转换为大写字母,我们可以按照以下步骤操作:
首先,创建一个具有字符串列的 data.table 对象。
然后,使用 sub 函数将字符串列中的首字母转换为大写字母。
示例
创建 data.table 对象
让我们创建一个如下所示的 data.table:
library(data.table) Countries<- sample(c("india","china","russia","croatia","uk","usa","sudan","nepal","korea","germany","iceland"),25,replace=TRUE) DT<-data.table(Countries) DT
输出
执行后,以上脚本生成以下输出(由于随机性,此输出在您的系统上可能会有所不同):
Countries 1: nepal 2: india 3: india 4: nepal 5: india 6: korea 7: germany 8: germany 9: sudan 10: iceland 11: india 12: india 13: nepal 14: korea 15: korea 16: nepal 17: croatia 18: nepal 19: usa 20: croatia 21: usa 22: india 23: nepal 24: germany 25: russia Countries
将首字母转换为大写字母
使用 sub 函数将 Countries 列中的首字母转换为大写字母:
library(data.table) Countries<- sample(c("india","china","russia","croatia","uk","usa","sudan","nepal","korea","germany","iceland"),25,replace=TRUE) DT<-data.table(Countries) DT$Countries_new<-sub("(.)", "\U\1",DT$Countries,perl=TRUE) DT
输出
Countries Countries_new 1: nepal Nepal 2: india India 3: india India 4: nepal Nepal 5: india India 6: korea Korea 7: germany Germany 8: germany Germany 9: sudan Sudan 10: iceland Iceland 11: india India 12: india India 13: nepal Nepal 14: korea Korea 15: korea Korea 16: nepal Nepal 17: croatia Croatia 18: nepal Nepal 19: usa Usa 20: croatia Croatia 21: usa Usa 22: india India 23: nepal Nepal 24: germany Germany 25: russia Russia Countries Countries_new
广告