% mutate(Compound = ifelse(str_detect" /> % mutate(Compound = ifelse(str_detect" /> % mutate(Compound = ifelse(str_detect"/>

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

37 Views Asked by At

Here's my code

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)

My desired output is methyl-ethylidene but it generates methyl- ethylidene, with a space in between the two strings.

But when my dataframe is

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

My desired output is methyl, ethylidene. Also I would like to extend this to strings that end with and and with. Can anyone help please? Thanks.

1

There are 1 best solutions below

0
dufei On

I think it's easier to check your condition if each part is in its own column:

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

Created on 2023-11-04 with reprex v2.0.2