【问题标题】:Iterating over words across vector of strings and applying change to single word遍历字符串向量中的单词并将更改应用于单个单词
【发布时间】: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


【解决方案1】:

您可以使用单个sapply 调用,即

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

【讨论】:

    【解决方案2】:

    这是一个基于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"
    

    【讨论】:

    • 到目前为止我最喜欢的解决方案,因为它可以灵活地识别单词和应用转换。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多