【发布时间】:2018-11-08 22:46:11
【问题描述】:
给定字符串:
words <- c("fauuucet water", "tap water")
我想对所有包含u的单词应用toupper函数。
期望的结果
res <- c("FAUUCET water", "tap water")
功能
change_u_case <- function(str) {
sapply(
X = str,
FUN = function(search_term) {
sapply(
X = strsplit(search_term, split = "\\s", perl = TRUE),
FUN = function(word) {
if (grepl(pattern = "u", x = word)) {
toupper(word)
}
}
,
USE.NAMES = FALSE
)
},
USE.NAMES = FALSE
)
}
测试
change_u_case(words) -> tst_res
words
tst_res
unlist(tst_res)
注意事项
- 我特别感兴趣的是是否可以构建使用单个
rapply调用的解决方案 -
rlist::list.iter方法也会很有趣 - 选择包含 u 字符的单词就是一个例子,在实践中我希望应用反映长度等的各种条件
【问题讨论】:
-
@Sotos 感谢您的贡献。它工作正常;我个人在想是否可以不执行两次
i[grepl('u', i)]并将其构建为function(word) {if/do}。如果没有更整洁的东西出现,如果您愿意提供答案,我很乐意接受您的解决方案。
标签: r string list apply sapply