给定字符串:
words <- c("fauuucet water", "tap water")
我想将 toupper
函数应用于包含 u
的所有单词。
期望的结果
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 字符的单词的选择就是一个例子,在实践中我会寻求应用反射(reflect)长度等的各种条件
最佳答案
您可以使用单个 sapply
调用,即
sapply(strsplit(words, ' '), function(i) {i1 <- grepl('u', i);
i[i1] <- toupper(i[i1]);
paste0(i, collapse = ' ')
})
#[1] "FAUUUCET water" "tap water"
关于r - 跨字符串向量迭代单词并将更改应用于单个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50598581/