Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting in R and preserving the order of occurence

Tags:

r

aggregate

Suppose I have generated a vector using the following statement:

x1 <- rep(4:1, sample(1:100,4))

Now, when I try to count the number of occurrences using the following commands

count(x1)
  x freq
1 1   40
2 2   57
3 3    3
4 4   46

or

as.data.frame(table(x1))
  x1 Freq
1  1   40
2  2   57
3  3    3
4  4   46

In both cases, the order of occurrence is not preserved. I want to preserve the order of occurrence, i.e. the output should be like this

  x1 Freq
1  4   46
2  3    3
3  2   57
4  1   40

What is the cleanest way to do this? Also, is there a way to coerce a particular order?

like image 762
user3212376 Avatar asked Jan 22 '26 15:01

user3212376


1 Answers

You are looking for rle function

rle(x1)
## Run Length Encoding
##   lengths: int [1:4] 12 2 23 52
##   values : int [1:4] 4 3 2 1
like image 70
bartektartanus Avatar answered Jan 24 '26 06:01

bartektartanus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!