Molia
Molia

Reputation: 311

Split string and remove duplicates from result

I have a string and would like to separate it by a certain character, (|), and then remove duplicates. How would I do that?

An example string:

conditionlst <- paste(c("excellent condition","perfect condition","good condition","used condition","great condition"),
                      collapse = "|")

I would like the output to look like the following:

"excellent" "perfect"   "good"      "used"      "great"     "condition"

How would I be able to do that? I tried using strsplit as below but cant get to show the result I want

strsplit(conditionlst, " ", fixed = TRUE)

Upvotes: 1

Views: 847

Answers (1)

akrun
akrun

Reputation: 887068

As the string is collapsed with |, we also need to split with | in addition to the space. Extract the list element and get the unique elements

unique(strsplit(conditionlst,"[| ]")[[1]])

Note that by placing the the characters to split inside the [], we are able to get the literal character instead of the metacharacter value which is relevant for the | (- meaning OR)

Upvotes: 3

Related Questions