我有 3 列。C1 和 C2 按 C0 分组。现在我想提取每个 C0 组中 C1 最大时满足的 C3 值。
df = data.frame(C0 = c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3),
C1 = c(0,2,3,6,2,0,0,4,9,7,1,2,7,4,2),
C2 = c("A","B", "C", "D", "E","A","B", "C", "D", "E","A","B", "C", "D", "E"))
现在我想添加一个新列 C4,它是 C2 的值,其中对应的 C1 在每个 C0 组中达到最大值。现在我只能提取最大 C1 的值,像这样
df %>% group_by(C0) %>% mutate (C4 = max(C1))
但是此代码返回的 C4 是每个 C0 组中 C1 的最大值的值。我不知道如何提取相应的C2值。另外,我不想只提取最大值的行,而是添加一个新列。像这样(由于我不允许附图,所以我用代码来解释这个想法:
df = data.frame(C0 = c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3),
C1 = c(0,2,3,6,2,0,0,4,9,7,1,2,7,4,2),
C2 = c("A","B", "C", "D", "E","A","B", "C", "D", "E","A","B", "C", "D", "E"),
C4 = c("D","D","D","D","D","D","D","D","D","D","C","C","C","C","C"))
非常感谢你帮助我!