与えられた文字列:
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
アプローチも興味深いでしょう - 次を含む単語の選択あなたは 文字は例であり、実際には長さなどを反映するさまざまな条件を適用しようとしています
回答 3 件
単一の
sapply
を使用できます 呼び出し、すなわちsapply(strsplit(words, ' '), function(i) {i1 <- grepl('u', i); i[i1] <- toupper(i[i1]); paste0(i, collapse = ' ') }) #[1] "FAUUUCET water" "tap water"
stringr
を試す :str_replace_all(words, '\\w*u\\w*', toupper) # [1] "FAUUUCET water" "tap water"
その他の例:
str_replace_all(c('Upset', 'day day up'), '\\w*u\\w*', toupper) # [1] "Upset" "day day UP"
これは
stringi
です ベースのソリューション: