我的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
我想rows
根据日期选择所有,例如,如果Date
大于2015-09-04
和小于2015-09-18
结果应该是:
Patch Date Prod_DL P1 2015-09-04 3.43 P11 2015-09-11 3.49
我尝试了以下但它返回空的空向量.
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)
但这给了我整个九月的数据.
是否有一种更有效的方法,比如在类型变量上使用between
运算符?dplyr
Date
如果日期格式正确date
,您的第一次尝试工作:
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
UPDATE
如果数据类型仍然有效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
另一个更详细的选项是使用该函数between
,x> = left&x <= right的快捷方式.我们需要更改=
占用标志的日期,并使用as.Date
(此处说明).
p2p_dt_SKILL_A%>% select(Patch,Date,Prod_DL)%>% filter(between(Date, as.Date("2015-09-05"),as.Date("2015-09-17")))