In: Math
Mary Jones
Tarik Mohammed
Smith, Jim
Tom O'Brian
Victor Lindquist
Chow, Vincent
Wong, Mary
Some names are in the format ‘First Last’ and others ‘Last, First’. Write a function to extract the full names, in the format ‘Last, First’, of all the individuals whose first name is ‘Mary’.
#R Code
#Loading Libraries
library(stringr)
#Given Names
name <- c("Mary Jones", "Tarik Mohammed", "Smith, Jim", "Tom
O'Brian",
"Victor Lindquist", "Chow, Vincent", "Wong, Mary")
#Function Creation
name_extract <- function(name_vector, first_name) {
df <- data.frame(Name = name_vector, FirstName = NA, LastName =
NA)
df$FirstName[str_detect(name, ",")] <- sub(".*, ", "",
df$Name[str_detect(name, ",")])
df$LastName[str_detect(name, ",")] <- sub(",.*", "",
df$Name[str_detect(name, ",")])
df$FirstName[!str_detect(name, ",")] <- sub(" .*", "",
df$Name[!str_detect(name, ",")])
df$LastName[!str_detect(name, ",")] <- sub(".* ", "",
df$Name[!str_detect(name, ",")])
df$Name <- as.character(df$Name)
extracted_names <- df$Name[df$FirstName == first_name]
return(extracted_names)
}
#Result for the First Name Mary
mary <- name_extract(name_vector = name, first_name =
"Mary")
print(mary)
**If the answer does not match or any kind of confusion you have please comment