gpt4 book ai didi

r - dplyr 编程方式过滤最近一周

转载 作者:行者123 更新时间:2023-12-02 06:50:42 25 4
gpt4 key购买 nike

有效过滤最后/最近一周的最佳方法是什么(基于它可能不是一整周的数据)。

library(lubridate)
library(dplyr)

df <- data.frame(dates =
c("2014-12-17","2014-12-18","2014-12-21","2014-12-25","2014-12-26",
"2015-05-17","2015-05-18","2015-05-21","2015-05-25","2015-05-26",
"2016-06-17","2016-06-18","2016-06-21","2016-06-25","2016-06-26"))


df <- df %>% mutate(dates = ymd(dates),
the.year = year(dates),
the.week = week(dates))

#Filter the last week (as may not be complete)

我可以想出这样的解决方案

max.week <- df %>% filter(the.year == max(the.year)) %>%
filter(the.week == max(the.week)) %>%
group_by(the.year, the.week) %>%
summarise(count= n()) %>%
ungroup() %>%
mutate(max.week = paste(the.year, the.week,sep="-")) %>%
select(max.week) %>%
unlist(use.names = F)

df %>% filter(!paste(the.year, the.week, sep = "-") == max.week)
%>%

但必须有更简单的解决方案吗?

最佳答案

我能想到的最短的 dplyr-way 是

filter(df, !{yw <- interaction(the.year, the.week)} %in% yw[which.max(dates)])

但您可能希望将其分解以提高可读性:

df %>% 
mutate(yearweek = paste(the.year, the.week, sep = "-")) %>%
filter(!yearweek %in% yearweek[which.max(dates)])

删除 ! 以获得相反的效果。

关于r - dplyr 编程方式过滤最近一周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45168342/

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