Replace entire string by one specific word.

Hi, @ketan10! First of all, it is going to be much easier for folks around here to help if you include the data and code you've used to get to where you are stuck rather than just a screenshot. Without the data you are working with, I had to type a few rows of your table rather than simply copying and pasting. See this post for more information about best practices for writing questions and including a reproducible example (reprex).

As to your question, I find the most intuitive way to do this for a relative simply replace is using str_detect() from the stringr package. If the text you feed to str_detect() is found, it will return TRUE and if it is not found, it will return FALSE. I use str_detect() with mutate() and case_when() to do multiple conditional replacements within a single variable.

library(tidyverse)

df <- tribble(
  ~event_type,
  "Violence against civilans",
  "Battle-No change of territory",
  "Riots/Protests",
  "Battle Government regains territory"
  )

df %>%
  mutate(event_type = case_when(
    str_detect(event_type, "Battle") ~ "Battle",
    str_detect(event_type, "Riots")  ~ "Riot",
    TRUE ~ event_type
    )
  )
#> # A tibble: 4 x 1
#>   event_type               
#>   <chr>                    
#> 1 Violence against civilans
#> 2 Battle                   
#> 3 Riot                     
#> 4 Battle

Created on 2018-10-30 by the reprex package (v0.2.1)

6 Likes