R lang:首字母大写

时间:2018-07-01 01:56:26

标签: r data-conversion

我正在尝试将列中的所有数据转换为“首字母大写” 以下代码将所有数据替换为第一行

simpleCap <- function(x) {
  s <- strsplit(x, " ")[[1]]
  paste(toupper(substring(s, 1,1)), substring(s, 2),
        sep="", collapse=" ")
}
allDestination$Categories <- simpleCap(allDestination$Categories)

样本数据

japan/okinawa/okinawa-other-islands
japan/hokkaido/hokkaido-north/furano-biei-tomamu
japan/hokkaido/hokkaido-north/asahikawa-sounkyo
japan/hokkaido/hokkaido-north/wakkanai-rishiri-rebun
japan/hokkaido/hokkaido-east/kushiro-akan-nemuro

功能代码示例来自 First letter to upper case

如何使函数成为“列兼容”而不是仅替换单个值?

2 个答案:

答案 0 :(得分:1)

您可以在后面使用否定的外观,以大写每个以非字母开头或在句子开头的字母,即(?:^|(?<=\\W))(.),也可以将其视为大写不以字母开头,即(?<!\\w)(.)

gsub("(?<!\\w)(.)","\\U\\1",dat1$V1,perl = TRUE) 

[1] "Japan/Okinawa/Okinawa-Other-Islands"                 
[2] "Japan/Hokkaido/Hokkaido-North/Furano-Biei-Tomamu"    
[3] "Japan/Hokkaido/Hokkaido-North/Asahikawa-Sounkyo"     
[4] "Japan/Hokkaido/Hokkaido-North/Wakkanai-Rishiri-Rebun"
[5] "Japan/Hokkaido/Hokkaido-East/Kushiro-Akan-Nemuro"    

数据:

 dat1=read.table(strip=T,text="japan/okinawa/okinawa-other-islands
       japan/hokkaido/hokkaido-north/furano-biei-tomamu
       japan/hokkaido/hokkaido-north/asahikawa-sounkyo
       japan/hokkaido/hokkaido-north/wakkanai-rishiri-rebun
       japan/hokkaido/hokkaido-east/kushiro-akan-nemuro")

答案 1 :(得分:1)

Tidyverse答案-此 stringr :: str_to_title

有专门的功能
library(tidyverse)

数据示例:

data_1 <- 
  data.frame("japan/okinawa/okinawa-other-islands",
             "japan/hokkaido/hokkaido-north/furano-biei-tomamu",
             "japan/hokkaido/hokkaido-north/asahikawa-sounkyo",
             "japan/hokkaido/hokkaido-north/wakkanai-rishiri-rebun",
             "japan/hokkaido/hokkaido-east/kushiro-akan-nemuro",
             stringsAsFactors=FALSE)

工作功能:

> str_to_title(data_1)

[1] "Japan/Okinawa/Okinawa-Other-Islands"                 
[2] "Japan/Hokkaido/Hokkaido-North/Furano-Biei-Tomamu"    
[3] "Japan/Hokkaido/Hokkaido-North/Asahikawa-Sounkyo"     
[4] "Japan/Hokkaido/Hokkaido-North/Wakkanai-Rishiri-Rebun"
[5] "Japan/Hokkaido/Hokkaido-East/Kushiro-Akan-Nemuro"  

https://stringr.tidyverse.org/reference/case.html