1

I'm looking for a mode function in R which I can use for dplyr. The two posts I have seen treats "ties" very differently. This post (Ken Williams) treats ties by selecting the first-appearing value of the set of modes. This post treats ties by noting both values in the same cell.

I'm looking a mode function that treat ties as NA AND excludes missing values. I used Gregor's post to treat ties as NA, but I can't seem to exclude the missing values.

The variable DF$Color is a character type.

Here's an example DF

Category<-c("A","B","B","C","A","A","A","B","C","B","C","C", "D", "D")
Color<-c("Red","Blue","Yellow","Blue","Green","Blue","Green","Yellow","Blue","Red","Red","Red","Yellow", NA)
DF<-data.frame(Category,Color)
DF <- arrange(DF, Category)
DF
DF$Color <- as.character(DF$Color)

With NA included, the code looks like:

 mode <- function(x) {
  ux <- unique(x)
  tx <- tabulate(match(x, ux))
  if(length(unique(tx)) == 1) {
    return(NA)
  }
  max_tx <- tx == max(tx)
  return(ux[max_tx])
}

    DF %>%
      group_by(Category) %>%
      summarise(Mode = mode(Color))

I'm trying to figure out the code that excludes the NA. The df would look like:

  Category Mode  
  <fct>    <fct> 
1 A        Green 
2 B        Yellow
3 C        NA    
4 D        Yellow
Kristine
  • 171
  • 5

1 Answers1

3

The following changes to the function ensure that the correct type of NA value is returned depending on the input and that it works with vectors of length 1.

mode <- function(x) {
  ux <- unique(na.omit(x))
  tx <- tabulate(match(x, ux))
  if(length(ux) != 1 & sum(max(tx) == tx) > 1) {
    if (is.character(ux)) return(NA_character_) else return(NA_real_)
  }
  max_tx <- tx == max(tx)
  return(ux[max_tx])
}

DF %>%
  group_by(Category) %>%
  summarise(Mode = mode(Color))

# A tibble: 4 x 2
  Category Mode  
  <fct>    <chr> 
1 A        Green 
2 B        Yellow
3 C        NA    
4 D        Yellow
Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56