当R中满足某些条件时,如何合并中间没有空格的字符串和带有空格的字符串?

How to merge strings with no space in between and with a space when certain conditions are met in R?

提问人:Catalyst 提问时间:11/4/2023 最后编辑:Wiktor StribiżewCatalyst 更新时间:11/4/2023 访问量:32

问:

这是我的代码

library(dplyr)    

df <- data.frame(

  Compound = c("methyl-", "ethylidene")
)

merged_string_df <- df %>%
  mutate(Compound = ifelse(str_detect(Compound, "\\ $(and|,|with)$"),  
                               str_c(Compound, " "), 
                               Compound)) %>%
  pull(Compound) %>%
  paste(collapse=" ")

print(merged_string_df)

我想要的输出是,但它生成 ,两个字符串之间有一个空格。methyl-ethylidenemethyl- ethylidene

但是当我的数据帧是

df <- data.frame(
      Compound = c("methyl,", "ethylidene")
    )

我想要的输出是.此外,我想将其扩展到以 和 结尾的字符串。谁能帮忙?谢谢。methyl, ethylideneandwith

字符串 r-collapse

评论


答:

0赞 dufei 11/4/2023 #1

我认为如果每个部分都在自己的列中,则更容易检查您的状况:

library(tidyverse)

df <- tribble(
  ~part1, ~part2,
  "methyl-", "ethylidene",
  "methyl,", "ethylidene",
  "methyl and", "ethylidene"
)

df |> 
  mutate(collapsed = if_else(
    str_detect(part1, "-$"),
    str_c(part1, part2),
    str_c(part1, part2, sep = " ")
  ))
#> # A tibble: 3 × 3
#>   part1      part2      collapsed            
#>   <chr>      <chr>      <chr>                
#> 1 methyl-    ethylidene methyl-ethylidene    
#> 2 methyl,    ethylidene methyl, ethylidene   
#> 3 methyl and ethylidene methyl and ethylidene

创建于 2023-11-04 with reprex v2.0.2