Uppercase the first letter in data frame

元气小坏坏 提交于 2019-12-08 21:53:12

问题


Heres my data,

> data
   Manufacturers       Models
1   audi                RS5  
2   bmw                 M3  
3   cadillac            CTS-V  
4   lexus               ISF

And I would want to uppercase the first letter in the first column, like this:

> data
   Manufacturers       Models
1   Audi                RS5  
2   Bmw                 M3  
3   Cadillac            CTS-V  
4   Lexus               ISF

I would appreciate any help on this question. Thanks a lot.


回答1:


Taking the example from the documentation for ?toupper and modifying it a bit:

capFirst <- function(s) {
    paste(toupper(substring(s, 1, 1)), substring(s, 2), sep = "")
}

data$Manufacturers <- capFirst(data$Manufacturers)
> data
#   Manufacturers Models
# 1          Audi    RS5
# 2           Bmw     M3
# 3      Cadillac  CTS-V
# 4         Lexus    ISF



回答2:


Or, taking an example from ?gsub:

data$Manufacturers <- gsub("^(\\w)(\\w+)", "\\U\\1\\L\\2", 
  data$Manufacturers, perl = TRUE)

> data
>  Manufacturers Models
1          Audi    RS5
2           Bmw     M3
3      Cadillac  CTS-V
4         Lexus    ISF


来源:https://stackoverflow.com/questions/16249570/uppercase-the-first-letter-in-data-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!