-2
Names <- c("SUSAN,ALTOP","Brent,SPINER","KIM,YAMAGUCHI","John,McMurphy","Kevin,Y")
City <- c("Toronto","New York","Chicago","Toronto","Tokyo")
DF <- data.frame(Names,City)

I'm hoping to create a function that will capitalize the first and last names in the simple example data frame above so that the names read as "Susan Altop","Brent Spiner"...etc. (Notice that I've also removed the commas.)

I can accomplish this using the following codes, either separately or with piping. But I'm hoping to create a function since I'll have to do this many times, but I'm not sure how to do that when using dplyr, tidyr, etc. I'm also open to more creative suggestions that use lists and purrr, if possible.

DF <- DF %>% separate(DF,Names,c("First","Last",sep=","),remove=TRUE)
DF <- DF %>% mutate_each(funs(tolower),First,Last)
DF <- DF %>% mutate_each(funs(Capitalize),First,Last)
DF <- DF %>% mutate(NewNames=paste0(First," ",Last)
Psidom
  • 209,562
  • 33
  • 339
  • 356
Mike
  • 2,017
  • 6
  • 26
  • 53
  • I have a function I wrote to do this a long time ago, but it doesn't use any special packages. Do you want it? it works with McName, Arabic names, etc. – Hack-R Aug 15 '16 at 22:19
  • If your problem is in writing a function, you should be clear about what your inputs and outputs are. You want to give it a data frame? Do you want to capitalize all columns? Does your function need to guess whether or not to separate by commas? Will you guarantee all columns are strings? Are there other arguments you want to give it? – Gregor Thomas Aug 15 '16 at 22:26
  • Not that I really recommend this approach, but: `library(tidyr) ; library(dplyr) ; DF %>% separate(Names, c('First', 'Last')) %>% mutate_at(vars(-City), funs(paste0(substr(., 1, 1), tolower(substr(., 2, nchar(.)))))) %>% unite(Names, First, Last, sep = ' ')` Pretty much any technique is going to kill the second "M" of "McMurphy", though. – alistaire Aug 15 '16 at 23:32

1 Answers1

5

There is the stri_trans_totitle function from stringi package which seems to do what you are looking for:

library(dplyr); library(stringi)
DF %>% mutate(Names = stri_trans_totitle(gsub(",", " ", Names)))

#           Names     City
# 1   Susan Altop  Toronto
# 2  Brent Spiner New York
# 3 Kim Yamaguchi  Chicago
# 4 John Mcmurphy  Toronto
# 5       Kevin Y    Tokyo

Or use str_to_title from stringr:

library(stringr)
DF %>% mutate(Names = str_to_title(gsub(",", " ", Names)))

#           Names     City
# 1   Susan Altop  Toronto
# 2  Brent Spiner New York
# 3 Kim Yamaguchi  Chicago
# 4 John Mcmurphy  Toronto
# 5       Kevin Y    Tokyo
Psidom
  • 209,562
  • 33
  • 339
  • 356