Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing everything from a string column conditional on another string column in R

I try to clean up a column containing long speeches during a debate. Right now, every row starts with a new speaker, however, things like subheaders remain at the end of each speech, which is not desirable.

Here is some example data:

speeches <- tibble(subheader = c("3.Discussion", "8.Voting"),
                   full_speech = c("I close this part. 3.Discussion Let's start with",
                                   "I think we can vote now")
                   )

Desired Outcome:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

subheader      full_speech
3. Discussion  I close this part.
8. Voting      I think we can vote now

What I tried so far:

speeches %>%
    mutate(full_speech = str_remove(full_speech, subheader))

But of course this only deletes the subheaders and not what follows after them.

>Solution :

We can paste the subheader with .* to match any characters that succeeds the subheader

library(dplyr)
library(stringr)
speeches %>% 
  mutate(full_speech = str_remove(full_speech, str_c("\\s+", 
      subheader, ".*")))

-output

# A tibble: 2 × 2
  subheader    full_speech            
  <chr>        <chr>                  
1 3.Discussion I close this part.     
2 8.Voting     I think we can vote now
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading