如何对字符串向量中含u的单词应用toupper?求rapply等实现方案
当然可以用单次rapply调用搞定这个需求,另外rlist::list.iter也有对应的实现方案,下面给你详细拆解两种方法:
问题背景
我们先明确基础的输入、需求和原有实现:
- 输入字符串向量:
words <- c("fauuucet water", "tap water")
- 核心需求:对其中包含字符
u的所有单词应用toupper函数,期望结果:
res <- c("FAUUCET water", "tap water")
- 原有基于嵌套
sapply的实现:
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实现的方案
rapply是专门用来递归处理嵌套列表的函数,我们可以利用它的特性简化实现,步骤很清晰:
- 先把每个字符串拆成单词组成的嵌套列表
- 用
rapply递归遍历每个单词,对符合条件的单词做转大写处理 - 最后把处理后的单词列表拼接回原字符串格式
具体代码:
change_u_case_rapply <- function(str) { # 拆分字符串为单词嵌套列表 word_lists <- strsplit(str, "\\s", perl = TRUE) # 递归处理每个单词:含u则转大写,否则保留原词 processed <- rapply( word_lists, function(word) if (grepl("u", word)) toupper(word) else word, how = "replace" # 保持原列表结构,替换对应元素 ) # 拼接回完整字符串 sapply(processed, paste, collapse = " ") } # 测试验证 tst_res_rapply <- change_u_case_rapply(words) tst_res_rapply # 输出结果:[1] "FAUUCET water" "tap water"
这个方案扩展性很强——你提到的用长度等其他条件筛选单词,只需要修改grepl("u", word)这部分判断逻辑即可。
用rlist::list.iter实现的方案
rlist包的list.iter提供了更灵活的列表迭代方式,这里给你两种实现思路:
首先确保安装并加载rlist包:
install.packages("rlist") library(rlist)
方案1:结合list.map的简洁实现
change_u_case_listiter <- function(str) { word_lists <- strsplit(str, "\\s", perl = TRUE) # 迭代每个单词列表,处理符合条件的单词 processed <- list.map( word_lists, lapply(.x, function(word) if (grepl("u", word)) toupper(word) else word) ) # 拼接回字符串 sapply(processed, paste, collapse = " ") } # 测试 tst_res_listiter <- change_u_case_listiter(words) tst_res_listiter # 输出结果:[1] "FAUUCET water" "tap water"
方案2:手动使用list.iter迭代(更灵活)
如果需要在迭代过程中做更复杂的逻辑(比如记录状态、多条件组合判断),可以手动用list.iter遍历:
change_u_case_listiter2 <- function(str) { word_lists <- strsplit(str, "\\s", perl = TRUE) processed <- lapply(word_lists, function(sentence) { # 创建迭代器 iter <- list.iter(sentence) result <- c() # 遍历迭代器处理每个单词 while (!iter$done()) { word <- iter$next() result <- c(result, if (grepl("u", word)) toupper(word) else word) } # 拼接成完整句子 paste(result, collapse = " ") }) unlist(processed) } # 测试 tst_res_listiter2 <- change_u_case_listiter2(words) tst_res_listiter2 # 输出结果:[1] "FAUUCET water" "tap water"
内容的提问来源于stack exchange,提问作者Konrad
相关产品推荐
相关产品推荐

