gpt4 book ai didi

R dplyr 根据乐趣索引(另一列)总结一个列值

转载 作者:行者123 更新时间:2023-12-04 17:18:17 24 4
gpt4 key购买 nike

我有一个这样的数据框,并希望在最后显示所需的输出。相反,我在中间得到了 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获取 max 的数字索引可用于子集 'y' 元素的值。使用 max只给出 z 的最大值.

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

关于R dplyr 根据乐趣索引(另一列)总结一个列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30057093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com