str_remove assistance

library(stringr)
library(dplyr)

DF <- data.frame(Text= c("cat_loves_dog",
                          "dog_love_cat",
                          "me_ow_sith_love",
                          "animal_cat_do",
                          "dog_love_kiss",
                          "monkey_see_do"))
DF <- DF |> 
   mutate(data_manip = str_remove(str_extract(Text, "_[^_]+$"),"^_do$"))
DF
             Text data_manip
1   cat_loves_dog       _dog
2    dog_love_cat       _cat
3 me_ow_sith_love      _love
4   animal_cat_do           
5   dog_love_kiss      _kiss
6  monkey_sith_see_do

above is my final dataset. I want to create a column called text_new which removes the string in data_manip from the string in text... but also removes any mention of the word "Sith" and its preceding hyphen "" and the word "Lime" and its preceding hyphen "".

note if there is no string in "data_manip" it should be appearing as is. unless there is the word "sith" or "lime" of course. thank u so very much. What I want:

       Text         data_manip   text_new
1   cat_loves_dog       _dog    cat_love
2    dog_love_cat       _cat    dog_love
3 me_ow_sith_love      _love    me_ow
4   animal_cat_do               animal_cat_do
5   dog_love_kiss      _kiss    dog_love
6   monkey_sith_see_do          monkey_see_do

I believe this code gets to your final result.

DF <- data.frame(Text= c("cat_loves_dog",
                         "dog_love_cat",
                         "me_ow_sith_love",
                         "animal_cat_do",
                         "dog_love_kiss",
                         "monkey_see_do"))
DF2 <- DF |> 
  mutate(data_manip = str_remove(str_extract(Text, "_[^_]+$"),"^_do$")) |>
  mutate(data_manip = ifelse(data_manip == '', NA, data_manip)) |>
  mutate(text_new = str_replace_all(Text, '_(S|s)ith|(L|l)ime', '')) |>
  mutate(text_new = ifelse(is.na(data_manip), text_new, str_replace(text_new, data_manip, '')))

DF
#>              Text
#> 1   cat_loves_dog
#> 2    dog_love_cat
#> 3 me_ow_sith_love
#> 4   animal_cat_do
#> 5   dog_love_kiss
#> 6   monkey_see_do
DF2
#>              Text data_manip      text_new
#> 1   cat_loves_dog       _dog     cat_loves
#> 2    dog_love_cat       _cat      dog_love
#> 3 me_ow_sith_love      _love         me_ow
#> 4   animal_cat_do       <NA> animal_cat_do
#> 5   dog_love_kiss      _kiss      dog_love
#> 6   monkey_see_do       <NA> monkey_see_do

Created on 2022-09-02 with reprex v2.0.2.9000

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.