user1723765
user1723765

Reputation: 6399

Identifying most frequent fractional numbers in vector

I have a vector that contains fractional numbers:

a<-c(0.5,0.5,0.3,0.5,0.2)

I would like to determine the most frequent (i.e. majority) number in the vector and return that number.

table(a) doesn't work because it will return the whole table. I want it to return only 0.5.

In case of ties I would like to choose randomly.

I have a function that does this for integers:

function(x){ 
    a<-tabulate(x,nbins=max(x)); b<-which(a==max(a))
if (length(b)>1) {a<-sample(b,1)} else{b}
}

However, this won't work for fractions.

Can someone help?

Upvotes: 0

Views: 52

Answers (1)

Chitrasen
Chitrasen

Reputation: 1726

You can use

names(which.max(table(a)))

If you want the numeric one as in your case, then coerce it to numeric

as.numeric(names(which.max(table(a))))

To randomize the tie case, you can add randomize the table

as.numeric(names(which.max(sample(table(a))))) #note this works only if length(unique(a)) > 1

Upvotes: 3

Related Questions