Given string:
words <- c("fauuucet water", "tap water")
I would like to apply toupper
function to all words that contain 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
call could be buildrlist::list.iter
approach would be also interesting Here is a stringi
-based solution:
library(stringi);
sapply(stri_extract_all_words(words),
function(w) paste(ifelse(stri_detect(w, regex = "u"), toupper(w), w), collapse = " "))
#[1] "FAUUUCET water" "tap water"