说我有以下矢量
x <- c('One', 'TWO', 'THREE / FOUR')
Run Code Online (Sandbox Code Playgroud)
我想转换TWO和THREE / FOUR对Two和Three / Four分别.我已经看了一下casefold()整个chartr()帮助页面,但无法弄清楚这一点.
在我真正的问题中,我有一个1500字符串的向量,我打算在其中检测以全部大写字母写的条目(我知道它们中的许多都包含斜线,就像上面示例中的斜杠一样)并将它们转换为start case.
我可以做的一件事是运行grepl('^[A-Z]+$', x)(由tenub建议),但它没有检测到THREE / FOUR全部大写(它产生[1] FALSE TRUE FALSE).从我所看到的,只有空间的存在足以让这种回归FALSE.
删除锚点grepl('[A-Z]+$', x)(由TheGreatCO建议)适用于上面的示例,但在下一个示例中失败:
y <- "Imposto Territorial Rural - ITR"
grepl('[A-Z]+', y)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
此外,无论我尝试什么,包含重音符号的元素总是被遗漏:
z <- c('Á')
grepl('[A-Z]+', z)
[1] FALSE
Run Code Online (Sandbox Code Playgroud)
部分内容是包中的演示示例gsubfn.您可以在安装包后运行它demo(gsubfn::gsubfn-lower).
x <- c('One', 'TWO', 'THREE / FOUR', 'ÁÁÁ')
library(gsubfn)
## find indices of vector where there are no lowercase letters
## (therefore all letters must be uppercase)
idx <- grep("[[:lower:]]", x, invert = TRUE)
## in these indices, run tolower on characters
## that do not follow a word boundary \\B
x[idx] <- gsubfn("\\B.", tolower, x[idx], perl = TRUE)
# [1] "One" "Two" "Three / Four" "Ááá"
Run Code Online (Sandbox Code Playgroud)
这两个\B和[:lower:]的区域设置相关的Sys.getlocale("LC_CTYPE").我的是"English_United States.1252".你的旅费可能会改变.