如何在R中按条件合并字符串:按需添加或省略空格
解决R中字符串条件合并的问题
原代码存在两个核心问题:
- 正则表达式错误:
"\ $(and|,|with)$"里的\ $属于多余且错误的写法,无法正确匹配以and、,、with结尾的字符串。 - 拼接逻辑错误:使用
paste(collapse=" ")会强制给所有元素之间添加空格,覆盖了你之前的条件处理,导致非目标字符串也被额外加了空格。
修改后的代码
library(dplyr) library(stringr) # 测试用例1:非目标结尾的字符串 df1 <- data.frame(Compound = c("methyl-", "ethylidene")) merged1 <- df1 %>% mutate(Compound = ifelse(str_ends(Compound, c("and", ",", "with")), str_c(Compound, " "), Compound)) %>% pull(Compound) %>% str_c(collapse = "") print(merged1) # 输出 "methyl-ethylidene" # 测试用例2:以逗号结尾的字符串 df2 <- data.frame(Compound = c("methyl,", "ethylidene")) merged2 <- df2 %>% mutate(Compound = ifelse(str_ends(Compound, c("and", ",", "with")), str_c(Compound, " "), Compound)) %>% pull(Compound) %>% str_c(collapse = "") print(merged2) # 输出 "methyl, ethylidene" # 测试用例3:以and结尾的字符串 df3 <- data.frame(Compound = c("test and", "abc")) merged3 <- df3 %>% mutate(Compound = ifelse(str_ends(Compound, c("and", ",", "with")), str_c(Compound, " "), Compound)) %>% pull(Compound) %>% str_c(collapse = "") print(merged3) # 输出 "test and abc" # 测试用例4:以with结尾的字符串 df4 <- data.frame(Compound = c("hello with", "world")) merged4 <- df4 %>% mutate(Compound = ifelse(str_ends(Compound, c("and", ",", "with")), str_c(Compound, " "), Compound)) %>% pull(Compound) %>% str_c(collapse = "") print(merged4) # 输出 "hello with world"
关键修改说明
- 替换正则匹配为
str_ends:str_ends是stringr包中专门用于判断字符串结尾的函数,比str_detect配合正则更直观准确,直接传入目标后缀向量即可。 - 调整拼接方式:用
str_c(collapse = "")替代paste(collapse=" "),这样完全按照处理后的字符串内容拼接,不会强制添加额外空格——符合条件的字符串已经手动加了空格,不符合的则直接拼接。
内容的提问来源于stack exchange,提问作者Catalyst
相关产品推荐
相关产品推荐

