R dplyr 根据 fun 索引(另一列)总结一列值

R dplyr summarise one column value based on index of fun(another column)

我有一个这样的数据框,并希望在最后显示所需的输出。相反,我在中间得到了 NA 输出。有什么方法可以使用 dplyr 做我想做的事吗?

x <- c(1234, 1234, 1234, 5678, 5678)
y <- c(95138, 30004, 90038, 01294, 15914)
z <- c('2014-01-20', '2014-10-30', '2015-04-12', '2010-2-28', '2015-01-01')
df <- data.frame(x, y, z)
df$z <- as.Date(df$z)
df %>% group_by(x) %>% summarise(y = y[max(z)])

What I get:
     x  y
1 1234 NA
2 5678 NA

Desired Output:
     x     y 
1 1234 90038
2 5678 15914

您可以尝试 which.max 获取可用于子集 'y' 元素的 max 值的数字索引。使用 max 仅给出 z.

的最大值
df %>%
    group_by(x) %>%
    summarise(y= y[which.max(z)])
#     x     y
#1 1234 90038
#2 5678 15914

dplyr中使用filtermax

df%>%group_by(x)%>%filter(z==max(z))