Mary Jones     Tarik Mohammed     Smith, Jim     Tom O'Brian     Victor Lindquist     Chow, Vincent     Wong, Mary Some names are in the format ‘First Last’...

Free

70.2K

Verified Solution

Question

Basic 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’.

Answer & Explanation Solved by verified expert
4.0 Ratings (412 Votes)

#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


Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students