Question

In: Math

Mary Jones     Tarik Mohammed     Smith, Jim     Tom O'Brian     Victor Lindquist     Chow, Vincent     Wong, Mary Some names...

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

Solutions

Expert Solution

#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


Related Solutions

CT13.4 Tom Epps and Mary Jones are examining the following statement of cash flows for Guthrie...
CT13.4 Tom Epps and Mary Jones are examining the following statement of cash flows for Guthrie Company for the year ended January 31, 2020. Guthrie Company Statement of Cash Flows For the Year Ended January 31, 2020 Sources of cash  From sales of merchandise $380,000  From sale of capital stock 420,000  From sale of investment (purchased below) 80,000  From depreciation 55,000  From issuance of note for truck 20,000  From interest on investments 6,000 Total sources of cash 961,000 Uses of...
Jim Smith and Bob Jones are new summer interns working for a major insurance company. During...
Jim Smith and Bob Jones are new summer interns working for a major insurance company. During their lunch break each day, they eat at a local sandwich shop. One day, Bob’s girlfriend joins you for lunch. When the bill arrives, Bob pays and tells Jim he will submit the bill for expense reimbursement as a business expense. Bob treats his girlfriend to lunch in this manner several times during the next month. You always ask for separate checks and pay...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT