在dplyr中过滤日期 [英] Filtering dates in dplyr
本文介绍了在dplyr中过滤日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的tbl_df:
> p2p_dt_SKILL_A%>%
+ select(Patch,Date,Prod_DL)%>%
+ head()
Patch Date Prod_DL
1 P1 2015-09-04 3.43
2 P11 2015-09-11 3.49
3 P12 2015-09-18 3.45
...
4 P13 2015-12-06 3.57
5 P14 2015-12-13 3.43
6 P15 2015-12-20 3.47
例如,如果Date
大于2015-09-04
并且小于2015-09-18
I want to select all rows
based on the date for example if Date
is greater than 2015-09-04
and less than 2015-09-18
结果应为:
Patch Date Prod_DL
P1 2015-09-04 3.43
P11 2015-09-11 3.49
我尝试了以下操作,但是它返回了空的空向量.
I tried the following but it returns empty empty vector.
p2p_dt_SKILL_A%>%
select(Patch,Date,Prod_DL)%>%
filter(Date > "2015-09-04" & Date <"2015-09-18")
只需返回:
> p2p_dt_SKILL_A%>%
+ select(Patch,Date,Prod_DL)%>%
+ filter(Date > 2015-09-12 & Date <2015-09-18)
Source: local data table [0 x 3]
Variables not shown: Patch (fctr), Date (date), Prod_DL (dbl)
也尝试使用引号.
并使用lubridate
p2p_dt_SKILL_A%>%
select(Patch,Date,Prod_DL)%>%
#filter(Date > 2015-09-12 & Date <2015-09-18)%>%
filter(Patch %in% c("BVG1"),month(p2p_dt_SKILL_A$Date) == 9)%>%
arrange(Date)
但这给了我九月份的全部数据.
But this gives me whole September data.
是否有更有效的方法,例如在Date
类型变量上使用dplyr
中的between
运算符?
Is there a more efficient way like using the between
operator from dplyr
on Date
types variables?
推荐答案
如果将Date正确设置为date
格式,则您的第一次尝试有效:
If Date is properly formatted as a date
, your first try works:
p2p_dt_SKILL_A <-read.table(text="Patch,Date,Prod_DL
P1,9/4/2015,3.43
P11,9/11/2015,3.49
P12,9/18/2015,3.45
P13,12/6/2015,3.57
P14,12/13/2015,3.43
P15,12/20/2015,3.47
",sep=",",stringsAsFactors =FALSE, header=TRUE)
p2p_dt_SKILL_A$Date <-as.Date(p2p_dt_SKILL_A$Date,"%m/%d/%Y")
p2p_dt_SKILL_A%>%
select(Patch,Date,Prod_DL)%>%
filter(Date > "2015-09-04" & Date <"2015-09-18")
Patch Date Prod_DL
1 P11 2015-09-11 3.49
如果数据的类型为tbl_df
,则仍然有效.
Still works if data is of type tbl_df
.
p2p_dt_SKILL_A <-tbl_df(p2p_dt_SKILL_A)
p2p_dt_SKILL_A%>%
select(Patch,Date,Prod_DL)%>%
filter(Date > "2015-09-04" & Date <"2015-09-18")
Source: local data frame [1 x 3]
Patch Date Prod_DL
(chr) (date) (dbl)
1 P11 2015-09-11 3.49
这篇关于在dplyr中过滤日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文