Reputation: 127
I am doing data cleaning with dplyr. One of the things I want to do is to capitalize values in certain columns.
data$surname
john
Mary
John
mary
...
I suppose I have to use the mutate function of dplyr with something like this
titleCase <- function(x) {
+ s <- strsplit(as.character(x), " ")[[1]]
+ paste(toupper(substring(s, 1, 1)), substring(s, 2),
+ sep = "", collapse = " ")
+ }
But how to combine both? I get all kinds of errors or truncated data frames
Thanks
Upvotes: 5
Views: 10007
Reputation: 341
A little late to the party but you can use stringr
package
library(stringr)
library(dplyr)
example1 <- tibble(names = c("john" ,"Mary", "John", "mary"))
example1 %>%
mutate(names = str_to_title(names))
## names
## <chr>
## 1 John
## 2 Mary
## 3 John
## 4 Mary
This will still work if you want all terms capitalized
example2 <- tibble(names = c("john james" ,"Mary carey", "John Jack", "mary Harry"))
example2 %>%
mutate(names = str_to_title(names))
## names
## <chr>
## 1 John James
## 2 Mary Carey
## 3 John Jack
## 4 Mary Harry
If you only want the first term capitalized, str_to_sentence()
will work
example2 %>%
mutate(names = str_to_sentence(names))
## names
## <chr>
## 1 John james
## 2 Mary carey
## 3 John jack
## 4 Mary harry
Upvotes: 10
Reputation: 887028
We can use sub
sub("(.)", "\\U\\1", data$surname, perl=TRUE)
#[1] "John" "Mary" "John" "Mary"
Implementing in the dplyr
workflow
library(dplyr)
data %>%
mutate(surname = sub("(.)", "\\U\\1", surname, perl=TRUE))
If we need to do this on multiple columns
data %>%
mutate_each(funs(sub("(.)", "\\U\\1", ., perl=TRUE)))
Just to check
res <- data1 %>%
mutate(surname = sub("(.)", "\\U\\1", surname, perl=TRUE))
sum(grepl("[A-Z]", substr(res$surname, 1,1)))
#[1] 500000
data <- data.frame(surname=c("john", "Mary", "John", "mary"),
firstname = c("abe", "Jacob", "george", "jen"), stringsAsFactors=FALSE)
data1 <- data.frame(surname = sample(c("john", "Mary", "John", "mary"),
500000, replace=TRUE), stringsAsFactors=FALSE)
Upvotes: 9
Reputation: 23788
There is a dedicated function for this that you can try:
R.utils::capitalize(data$surname)
If this needs to be implemented into a dplyr
procedure, one could try the following:
library(dplyr)
library(R.utils)
data %>% mutate(surname = capitalize(surname))
Upvotes: 6