Reputation: 6399
I have a vector a<-replicate(100, round(runif(1)))
I would like to count which is more frequent 0 or 1.
I could use table(a)
but is there a more direct way to display the most frequently occurring number?
My problem with table(a):
a
is generated several times in the program and the most frequent number is recorded on each iteration. If I use table(a)
the first column will have the count of 0
s and the 2nd column the count of 1
s. Now I use b<-as.vector(table(a))
to directly get the counts and use b[1]
as the number of 0s and b[2]
as the number of 1s. Now if it happens that there are only 1s or only 0s in the vector then the length of b will be 1 and I will have no idea wether I have 100 1s or 100 0s.
Upvotes: 0
Views: 2045
Reputation: 17412
Why not just sum(a)
? If sum(a) > 50
, 1 is more frequent. It's a common technique for boolean values.
Upvotes: 3
Reputation: 4995
You could store the table in a data.frame
and then use which.max
adf<-data.frame(table(a))
adf[which.max(adf$Freq),1]
Upvotes: 0