问题描述
我想创建一个变量,其中包含对某个因素最频繁的观察。在模式中存在平局的情况下,我想使用第二列的值来打破平局。
例如:
person <- c("X","Y","Z","Z")
id<-c(0,1,1)
year<-c("2019","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
我想将 NA 替换为每个人/年组中 id
最高的 value
。所需的输出:
person year Mode
<chr> <chr> <dbl>
X 2019 0
Y 2019 1
Y 2020 1
Z 2020 1
2020 年 Z 的 id
现在是 1
,因为 id=1
的 value
(6) 高于
value
为 id=0
(3)
解决方法
我们可以将 NA 替换为对应于最大值 (which.max
) 的 'id'
library(dplyr)
library(tidyr)
test%>%
group_by(person,year)%>%
dplyr::summarise(Mode =replace_na(mode(id),id[which.max(value)]),.groups = 'drop')