Counting the number of elements with the values of x in a vector

后端 未结 19 1684
闹比i
闹比i 2020-11-22 02:44

I have a vector of numbers:

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
         453,435,324,34,456,56,567,65,34,435)

How can I hav

19条回答
  •  天涯浪人
    2020-11-22 03:25

    One option could be to use vec_count() function from the vctrs library:

    vec_count(numbers)
    
       key count
    1  435     3
    2   67     2
    3    4     2
    4   34     2
    5   56     2
    6   23     2
    7  456     1
    8   43     1
    9  453     1
    10   5     1
    11 657     1
    12 324     1
    13  54     1
    14 567     1
    15  65     1
    

    The default ordering puts the most frequent values at top. If looking for sorting according keys (a table()-like output):

    vec_count(numbers, sort = "key")
    
       key count
    1    4     2
    2    5     1
    3   23     2
    4   34     2
    5   43     1
    6   54     1
    7   56     2
    8   65     1
    9   67     2
    10 324     1
    11 435     3
    12 453     1
    13 456     1
    14 567     1
    15 657     1
    

提交回复
热议问题