Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R equivalent of SQL SELECT COUNT(*) ... GROUP BY

Tags:

r

count

group-by

I'm trying to find how to count the number of integers of each type in a vector. Eg, how many 1, 2, and 3 are there (without hard-coding == 1,2,3):

test_vec = c(1,2,3,1,2,1,2,1,1,1,2,1,3,1,2,3,2,1,2,1,3)

And, how to identify that I added some 4s to the vector and count them?

test_vec = c(test_vec,4,4,4)

I could do this with range() and a loop, but wondered if there is a general vectorised solution?

Edit: not the same question as this because that question doesn't ask about a generalised table situation (though the answers sensibly suggests it) but rather checking hard-coded equality sum(test_vec==x)

like image 680
Escher Avatar asked Oct 15 '25 10:10

Escher


2 Answers

aggregate is very handy in this situation

> aggregate(data.frame(count = test_vec), list(value = test_vec), length)

  value count
1     1    10
2     2     7
3     3     4
like image 79
SeaSprite Avatar answered Oct 18 '25 06:10

SeaSprite


you can use table

table(test_vec)
test_vec
 1  2  3 
10  7  4 
like image 27
Mamoun Benghezal Avatar answered Oct 18 '25 06:10

Mamoun Benghezal