Chapter 13 5. Create a Function

Now we can turn the title-extraction steps into a reusable function.

create_title <- function(firstname) {
  firstname %>%
    str_trim(side = "left") %>%
    str_extract("^[^.]+")
}

13.1 5.1 Test the Function

titanic <- titanic %>%
  mutate(Title_from_function = create_title(First_name))

head(titanic %>% select(First_name, Title, Title_from_function))
## # A tibble: 6 x 3
##   First_name                                 Title Title_from_function
##   <chr>                                      <chr> <chr>              
## 1 Mr. Owen Harris                            Mr    Mr                 
## 2 Mrs. John Bradley (Florence Briggs Thayer) Mrs   Mrs                
## 3 Miss. Laina                                Miss  Miss               
## 4 Mrs. Jacques Heath (Lily May Peel)         Mrs   Mrs                
## 5 Mr. William Henry                          Mr    Mr                 
## 6 Mr. James                                  Mr    Mr