在第二列中具有值的平局打破模式 -R

Tie breaking mode with values in a second column -R

我想创建一个包含最常观察到的因素的变量。在模式中出现平局的情况下,我想使用第二列的值来打破平局。

例如:

person <- c("X", "Y", "Z", "Y", "Y", "Z")
id<-c(0,1,0,1,1,1)
year<-c("2019", "2019", "2020", "2019", "2020", "2020")
value<-(c(1, 2, 3, 4, 5, 6))
test <- data.frame(person, id, year, value)
  person id year value
      X  0 2019     1
      Y  1 2019     2
      Z  0 2020     3
      Y  1 2019     4
      Y  1 2020     5
      Z  1 2020     6

这是我计算众数时得到的结果,其中 NA 当前用于表示平局:

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])
}

idmode<-test%>%group_by(person, year)%>%dplyr::summarise(Mode =mode(id))

  person year     Mode
  <chr>  <chr>   <dbl>
 X      2019        0
 Y      2019        1
 Y      2020        1
 Z      2020       NA

我想用每个 person/year 组中 value 最高的 id 替换 NA。期望的输出:

  person year     Mode
  <chr>  <chr>   <dbl>
 X      2019        0
 Y      2019        1
 Y      2020        1
 Z      2020        1

2020 年 Z 的 id 现在是 1,因为 id=1value (6) 高于 value 对于 id=0(3)

我们可以用对应于最大值(which.max)

的'id'替换NA
library(dplyr)
library(tidyr)
test%>%
   group_by(person, year)%>%
   dplyr::summarise(Mode =replace_na(mode(id), 
          id[which.max(value)]), .groups = 'drop')