迭代字符串向量中的单词并将更改应用于单个单词

时间:2018-05-30 07:18:20

标签: r string list apply sapply

给定字符串:

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 字符的单词就是一个例子,在实践中我会考虑应用反映长度的各种条件等等。

3 个答案:

答案 0 :(得分:2)

您可以使用单个sapply电话,即

sapply(strsplit(words, ' '), function(i) {i1 <- grepl('u', i); 
                                         i[i1] <- toupper(i[i1]); 
                                         paste0(i, collapse = ' ')
                                         })
#[1] "FAUUUCET water" "tap water"

答案 1 :(得分:1)

以下是基于stringi的解决方案:

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"

答案 2 :(得分:1)

尝试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"