R No Mode and Exclude NA

拜拜、爱过 提交于 2019-12-13 03:16:06

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/56552709/r-no-mode-and-exclude-na

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!