Rémy P
Rémy P

Reputation: 11

r - retrieve only the first word and the following letter from a string

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

Answers (3)

akrun
akrun

Reputation: 886968

Another option is

sub("[a-z]+$", "", x)
#[1] "FORD M"

data

x <- "FORD Mickael"

Upvotes: 0

effel
effel

Reputation: 1421

tab <- data.frame(name = "FORD Mickael")
tab$name <- gsub("(\\w)\\w*$", "\\1", tab$name)
# [1] "FORD M"

Upvotes: 3

nicola
nicola

Reputation: 24480

You can try:

require(stringr)
x<-"FORD Mickael"
str_extract(x,"^\\w+\\s+\\w")
#[1] "FORD M"

Upvotes: 3

Related Questions