gpt4 book ai didi

r - 查找带有日期的每年的最小值和最大值

转载 作者:行者123 更新时间:2023-12-02 07:16:39 27 4
gpt4 key购买 nike

我有一个庞大的数据集,我想要每个日期的最小值和最大值以及日期。

我的数据帧df看起来像这样:

Date       a  b  
01/20/2015 20 50
05/13/2015 60 70
10/18/2015 22 45
04/22/2016 15 40
04/25/2016 20 30
06/28/2016 33 45
01/01/2018 90 20
04/25/2018 50 30
10/19/2018 45 55

我想要这样的输出
Date       min.a max.a min.b max.b
01/20/2015 20
05/13/2015 70
10/18/2015 45
05/13/2015 70

其他年份也是如此。

我正在使用以下代码,但无法提取每年的日期。
我从日期列中提取了年份。
df$year<-format(df$date,"%y")
df%>%
group_by(a,b)%>%summarize(min(a),max(a),min(b),max(b))

但是我没有得到想要的输出。我想要每年带日期的min-max值。

最佳答案

以下代码可以正常工作,并且可以最大程度地完成所有工作,我认为应该很容易适应最小值(只需相应地重复代码)。


library(dplyr)

df %>%
group_by(year) %>%
mutate(max.a = max(a), max.b = max(b)) %>%
ungroup() %>%
mutate(max.a = case_when(a == max.a ~ max.a, TRUE ~ NA_real_), max.b = case_when(b == max.b ~ max.b, TRUE ~ NA_real_)) %>%
filter(!is.na(max.a) | !is.na(max.b)) %>%
select(-a,-b)

关于r - 查找带有日期的每年的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61319786/

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