一段时间以来,我一直试图找出这个问题。我有以下数据框,通过 ID 重复观察:
ID color
1 blue
1 red
1 blue
2 red
2 blue
2 red
.
.
.
我想通过为每个 ID 选择频率最高的颜色来创建一个新的数据框,以便每个 ID 只有 1 行。也就是说,我想获得以下数据框:
ID color
1 blue
2 red
3
.
.
.
我尝试使用transform
但没有奏效,因为它只对每个 ID 在数据中出现的次数求和。transform(df, freq.ID = ave(seq(nrow(df)), ID, FUN=length))
有没有办法做到这一点?
我们根据“ID”、“颜色”获取频率计数,创建一个带有频率的汇总“n”列,然后对“ID”上的行和desc
“n”的结束顺序进行排序,并使用distinct
返回第一个每个“ID”的唯一行
library(dplyr)
df1 %>%
count(ID, color) %>%
arrange(ID, desc(n)) %>%
select(-n) %>%
distinct(ID, .keep_all = TRUE)
-输出
# ID color
#1 1 blue
#2 2 red
df1 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L), color = c("blue",
"red", "blue", "red", "blue", "red")), class = "data.frame", row.names = c(NA,
-6L))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句