Package: stringr


Function: str_sub()


1. Extract the middle and last initials based on location

Review the data (d6)

# A tibble: 4 x 2
     id initials
  <dbl> <chr>   
1     1 cgl     
2     2 fwl     
3     3 kas     
4     4 rab     

Pull the middle and last initial.

  • Note: I can use negative numbers to count backwards from the end.
d6 %>%
  dplyr::mutate(ml_init = stringr::str_sub(initials, start = 2, end = -1))
# A tibble: 4 x 3
     id initials ml_init
  <dbl> <chr>    <chr>  
1     1 cgl      gl     
2     2 fwl      wl     
3     3 kas      as     
4     4 rab      ab     

2. Extract middle initials based on location

Review the data (d5)

# A tibble: 4 x 2
     id initials
  <dbl> <chr>   
1     1 cgl     
2     2 fwl     
3     3 kas     
4     4 rkab    

Notice some names have 2 middle initials.

d5 %>%
  dplyr::mutate(m_init = str_sub(initials, start = 2, end = -2))
# A tibble: 4 x 3
     id initials m_init
  <dbl> <chr>    <chr> 
1     1 cgl      g     
2     2 fwl      w     
3     3 kas      a     
4     4 rkab     ka    

Return to Strings