blanchey
blanchey

Reputation: 212

Unique Values in list

I have a vector with names such as

names <- c('John Smith','Emily Jones', 'John Marcus', 'Emily Stan', 'Tom Rhodes')

and I do

strsplit(names,' ')

which returns me a list of lists of the names. How can I get a list or vector of the unique first names which are John, Emily, Tom? I need to do x[[1]] to access a specific list so I'm not sure how to use unique in this case.

Upvotes: 1

Views: 40

Answers (2)

acylam
acylam

Reputation: 18661

With sub:

unique(sub("\\s\\w+", "", names))
# [1] "John"  "Emily" "Tom"

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388807

We could split the names on spaces using strsplit and then from each element of list get the first element and keep only the unique ones.

unique(sapply(strsplit(names, '\\s+'), "[[", 1))
#[1] "John"  "Emily" "Tom"  

Another option using word function from stringr package, where we can extract specific words from the string.

library(stringr)
unique(word(names))
#[1] "John"  "Emily" "Tom"  

Upvotes: 1

Related Questions