我有这个虚拟数据集。
sr <- c(1,1,1,2,2,2,2)
w_type <- c("a","b","a","c","c","c","d")
segment <- c("high","Low","high","high","low","high","low")
df <- data.frame(sr,w_type,segment)
对于每个sr号,我们需要具有唯一的w_type和segment。对于每个sr编号,w_type和segment必须是出现频率最高的w_type或segment。
我可以找到大多数发生的w_type,但不确定如何与原始数据帧结合。df %>% group_by(sr) %>% count(w_type) %>% top_n(1)
。以及“细分”的情况。当频率相等时,例如对于sr#2,我们有相等数量的“高”和“低”计数,在这种情况下,我要取两个段中“高”或“低”中的任何一个。
在这里,我们可以Mode
按“ sr”分组后找到带有功能的频率计数
library(dplyr)
df %>%
group_by(sr) %>%
mutate(new_segment = Mode(segment))
# A tibble: 7 x 4
# Groups: sr [2]
# sr w_type segment new_segment
# <dbl> <fct> <fct> <fct>
#1 1 a high high
#2 1 b Low high
#3 1 a high high
#4 2 c high high
#5 2 c low high
#6 2 c high high
#7 2 d low high
哪里
Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句