Import your data

# excel file
refugee <- read_excel("../00_data/mydata.xlsx") %>% janitor::clean_names()

Chapter 14

Tools

Detect matches

refugee %>% 
    summarise(sum(str_detect(the_year_of_data_collection, "8$")))
## # A tibble: 1 × 1
##   `sum(str_detect(the_year_of_data_collection, "8$"))`
##                                                  <int>
## 1                                                 5264
sum(str_detect(refugee$the_year_of_data_collection, "8$"))
## [1] 5264
mean(str_detect(refugee$the_year_of_data_collection, "8$"))
## [1] 0.08122329
refugee %>%
    mutate(col_2015 = str_extract(the_year_of_data_collection, "2015")) %>%
select(the_year_of_data_collection, col_2015) %>%
filter(!is.na(col_2015))
## # A tibble: 4,938 × 2
##    the_year_of_data_collection col_2015
##                          <dbl> <chr>   
##  1                        2015 2015    
##  2                        2015 2015    
##  3                        2015 2015    
##  4                        2015 2015    
##  5                        2015 2015    
##  6                        2015 2015    
##  7                        2015 2015    
##  8                        2015 2015    
##  9                        2015 2015    
## 10                        2015 2015    
## # ℹ 4,928 more rows

Replacing matches

refugee %>%
    mutate(col_2015_2 = str_replace(the_year_of_data_collection, "2015", "2032")) %>%
select(the_year_of_data_collection, col_2015_2)
## # A tibble: 64,809 × 2
##    the_year_of_data_collection col_2015_2
##                          <dbl> <chr>     
##  1                        2010 2010      
##  2                        2010 2010      
##  3                        2010 2010      
##  4                        2010 2010      
##  5                        2010 2010      
##  6                        2010 2010      
##  7                        2010 2010      
##  8                        2010 2010      
##  9                        2010 2010      
## 10                        2010 2010      
## # ℹ 64,799 more rows