Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
dplyr以编程方式筛选最近一周_R_Dplyr_Lubridate - Fatal编程技术网

dplyr以编程方式筛选最近一周

dplyr以编程方式筛选最近一周,r,dplyr,lubridate,R,Dplyr,Lubridate,有效过滤上一周/最近一周数据的最佳方法是什么(基于它可能不是一整周的数据) 库(lubridate) 图书馆(dplyr) df% 筛选器(the.week==max(the.week))%>% 按(年、周)分组%>% 汇总(计数=n())%>% 解组()%>% mutate(max.week=粘贴(the.year,the.week,sep=“-”))%>% 选择(最长周)%>% 未列出(use.names=F) df%>%filter(!paste(the.year,the.week,sep

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

库(lubridate)
图书馆(dplyr)
df%
筛选器(the.week==max(the.week))%>%
按(年、周)分组%>%
汇总(计数=n())%>%
解组()%>%
mutate(max.week=粘贴(the.year,the.week,sep=“-”))%>%
选择(最长周)%>%
未列出(use.names=F)
df%>%filter(!paste(the.year,the.week,sep=“-”==max.week)
%>%

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

我能想到的最短dplyr方法是

filter(df, !{yw <- interaction(the.year, the.week)} %in% yw[which.max(dates)])
删除
以达到相反的效果。

尝试以下方法:

df %>% transform(yw= the.year *100 + the.week) %>% filter(yw != max(yw)) %>% select(-yw)
或者,如果您的数据按日期排序,情况似乎是这样的:

df %>% filter(the.year !=last(the.year) | the.week !=last(the.week))

使用dplyr的另一种可能性是

df %>% 
arrange(dates) %>% 
filter(the.week != last(the.week) | the.year != last(the.year)) 

组索引也有助于:

df %>% 
  filter(group_indices(., the.year, the.week) < max(group_indices(., the.year, the.week)))
df%>%
过滤器(组指数(,.year,the.week)
也可以写为:

df %>% filter({id <- group_indices(., the.year, the.week)} < max(id))
df%>%筛选器({id%
变异(id=组指数(,.year,the.week))%>%
过滤器(id<最大(id))

您可以删除第一行中的外部
{}
。很好的分组。不知道该函数很好的答案。谢谢。最快的microbenchmark结果为100000行。@Axeman我在
R 3.3.1
dplyr 0.5.0
中有错误。第一个和第三个解决方案在mutate\u impl(.data,dots)中给出
错误:无法处理
,第二个sol在filter\u impl(.data,dots)中出现
错误:禁止分配
。因此我无法检查,但似乎您的解决方案只有在数据(或因子)排序时才起作用,不是吗?@Moody\u Mudscapper,您可能需要
dplyr v0.7.0
或更高版本,不确定。如果数据未排序,请使用
arrange(the.year,the.week)
首先。谢谢@Axeman.iboboru,您是否在基准测试中包含了我的排序数据解决方案?
df %>% 
arrange(dates) %>% 
filter(the.week != last(the.week) | the.year != last(the.year)) 
df %>% 
  filter(group_indices(., the.year, the.week) < max(group_indices(., the.year, the.week)))
df %>% filter({id <- group_indices(., the.year, the.week)} < max(id))
df %>% 
  mutate(id = group_indices(., the.year, the.week)) %>% 
  filter(id < max(id))