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