0

The below function calculated the Mode for my data. However, in case that the data freq are equal it chooses the first one. How is it possible to edit the Mode function so that if the values are same return the median value.

Mode <- function(x) {
  ux <- unique(x) 
  ux[which.max(tabulate(match(x, ux)))] }

for example in case

    id V   Freq 
1   A  40  1
2   B  23  1
3   C  3   1 

it returns 40, which I need to return 23 as median when the freqs are same.

Sean
  • 103
  • 9

1 Answers1

1

Changing the function of Mode from here you can do

Modes <- function(x) {
   ux <- unique(x)
   tab <- tabulate(match(x, ux))
   median(ux[tab == max(tab)])
}

Modes(df$V)
#[1] 23

In case when there is only one mode

df$V[2] <- 40
Modes(df$V)
#[1] 40

data

df <- structure(list(id = structure(1:3, .Label = c("A", "B", "C"), 
class = "factor"), V = c(40L, 23L, 3L), Freq = c(1L, 1L, 1L)), 
class = "data.frame", row.names = c("1", "2", "3"))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213