Reputation: 663
Say I have a factor myfac <- as.factor(c("A","A","B","B", "B", "C", "D", "D", "A","A","B","B", "C", "D", "D"))
.
I want to extract unique elements of this factor (not the levels). So the result I want is: A B C D A B C D
. How can I get this in R?
Upvotes: 2
Views: 40
Reputation: 887971
An option with rleid
library(data.table)
myfac[!duplicated(rleid(myfac))]
#[1] A B C D A B C D
Upvotes: 0
Reputation: 389325
Another option using head
and tail
to compare current and previous value :
myfac[c(1, which(tail(myfac, -1) != head(myfac, -1)) + 1)]
#[1] A B C D A B C D
#Levels: A B C D
Upvotes: 1
Reputation: 25208
Maybe something like:
rle(as.character(myfac))$values
#[1] "A" "B" "C" "D" "A" "B" "C" "D"
Upvotes: 3