Yamuna_dhungana
Yamuna_dhungana

Reputation: 663

Extract unique elements of each group of factor

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

Answers (3)

akrun
akrun

Reputation: 887971

An option with rleid

library(data.table)
myfac[!duplicated(rleid(myfac))]
#[1] A B C D A B C D

Upvotes: 0

Ronak Shah
Ronak Shah

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

chinsoon12
chinsoon12

Reputation: 25208

Maybe something like:

rle(as.character(myfac))$values
#[1] "A" "B" "C" "D" "A" "B" "C" "D"

Upvotes: 3

Related Questions