Uppercase the first letter in data frame

2019-06-20 06:43发布

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.

2条回答
狗以群分
2楼-- · 2019-06-20 07:25

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
查看更多
在下西门庆
3楼-- · 2019-06-20 07:28

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
查看更多
登录 后发表回答