Search code examples
rvectorcountelementvctrs

R - Counting elements in a vector


is there a way to count elements in a vector, without considering its unique values? For example, I have a vector vec <- as.vector(c("A","A","B","B","A","A","B","B")). I want to count the elements in the vector so it will return a vector of [1] 2 2 2 2 .

I have tried using the vec_count function in the vctrs package:

my_vec <- as.vector(c("A","A","B","B","A","A","B","B"))
my_count <- vec_count(my_vec, sort = "key")
my_count$count
[1] 4 4

But this function considers the unique elements in the vector, which is not what I want. Any ideas how to do this?


Solution

  • Since you are counting continual sequence here, we can use rle.

    rle(vec)$lengths
    #[1] 2 2 2 2
    

    Something similar with data.table rleid :

    table(data.table::rleid(vec))
    #1 2 3 4 
    #2 2 2 2