user27976
user27976

Reputation: 903

Getting unique rows of a table and their numbers

I have a dataframe:

id  y   z
oX  79  100
oX  23  46
oX  10  29
uM  12  90
uT  43  50
uT  13  99

I would like to keeep unique rows based on "id", and also keep track of the original number of each id as follows:

oX:3
uM:1
uT:2 

I konw that I can use either unique()/duplicated() for the first part, but unsure about how to keep record the original number of each unique row How can i do this? Thanks

Upvotes: 2

Views: 100

Answers (3)

Jilber Urbina
Jilber Urbina

Reputation: 61164

Just wanted to post another alternative, consider data.table

> library(data.table)
> data.table(mydf)[,.N, by="id"]
   id N
1: oX 3
2: uM 1
3: uT 2

Upvotes: 2

Julien Navarre
Julien Navarre

Reputation: 7830

this will do what you want :

> as.data.frame(table(a$id))
  Var1 Freq
1   oX    3
2   uM    1
3   uT    2

Upvotes: 2

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193527

Assuming your data.frame is called "mydf", table should work just fine:

table(mydf$id)
#
# oX uM uT 
#  3  1  2 

Upvotes: 2

Related Questions