Reputation: 11
I'd like to retrieve only the first word and the following letter from a String. The situation is the following:
I have a column in my data frame where there is the first and last name of someone.
Example:
FORD Mickael
but I'd like to only have his last name and the first letter of his first name (FORD M
in our example).
I only managed to get the first word from the string and not the following letter (using the word function from the stringr package).
Upvotes: 0
Views: 810
Reputation: 886968
Another option is
sub("[a-z]+$", "", x)
#[1] "FORD M"
x <- "FORD Mickael"
Upvotes: 0
Reputation: 1421
tab <- data.frame(name = "FORD Mickael")
tab$name <- gsub("(\\w)\\w*$", "\\1", tab$name)
# [1] "FORD M"
Upvotes: 3
Reputation: 24480
You can try:
require(stringr)
x<-"FORD Mickael"
str_extract(x,"^\\w+\\s+\\w")
#[1] "FORD M"
Upvotes: 3