R 按两个时间序列过滤数据帧
嗨,我是R的新手,想知道是否有一种简单的方法可以过滤多个日期的数据。 我有一份日期为2003年3月7日至2016年12月31日的数据。 我需要按多个时间序列分割/过滤数据,如下所示 新数据框中需要的日期: 2003年3月7日至2005年3月6日 和 2013年1月1日至2016年12月31日R 按两个时间序列过滤数据帧,r,dataframe,time,R,Dataframe,Time,嗨,我是R的新手,想知道是否有一种简单的方法可以过滤多个日期的数据。 我有一份日期为2003年3月7日至2016年12月31日的数据。 我需要按多个时间序列分割/过滤数据,如下所示 新数据框中需要的日期: 2003年3月7日至2005年3月6日 和 2013年1月1日至2016年12月31日 i、 e新数据框应不应包括2005年3月7日至2012年12月31日的日期让我们以以下数据框为日期: df <- data.frame( date = c(ymd("2017-02-02"),ymd(
i、 e新数据框应不应包括2005年3月7日至2012年12月31日的日期让我们以以下数据框为日期:
df <- data.frame( date = c(ymd("2017-02-02"),ymd("2016-02-02"),ymd("2014-02-01"),ymd("2012-01-01")))
date
1 2017-02-02
2 2016-02-02
3 2014-02-01
4 2012-01-01
或:
df2我会选择lubridate
。特别是
library(data.table)
library(lubridate)
set.seed(555)#in order to be reproducible
N <- 1000#number of pseudonumbers to be generated
date1<-dmy("07-03-2003")
date2<-dmy("06-03-2005")
date3<-dmy("01-01-2013")
date4<-dmy("31-12-2016")
可视化切割的一种好方法:
之前
欢迎来到StackOverflow!请阅读相关信息以及如何给出建议。这将使其他人更容易帮助你。
df2 <- filter(df, between(date, ymd("2013-01-01"), ymd("2014-04-01")))
date
1 2014-02-01
library(data.table)
library(lubridate)
set.seed(555)#in order to be reproducible
N <- 1000#number of pseudonumbers to be generated
date1<-dmy("07-03-2003")
date2<-dmy("06-03-2005")
date3<-dmy("01-01-2013")
date4<-dmy("31-12-2016")
my_dt<-data.table(date_sample=c(sample(seq(date1, date4, by="day"), N),numeric_sample=sample(N,replace = F)))
> head(my_dt)
date_sample numeric_sample
1: 2007-04-11 2
2: 2006-04-20 71
3: 2007-12-20 46
4: 2016-05-23 78
5: 2011-10-07 5
6: 2003-09-10 47
forbidden_dates<-interval(date2+1,date3-1)#create interval that dates should not fall in.
> forbidden_dates
[1] 2005-03-07 UTC--2012-12-31 UTC
test_date1<-dmy("08-03-2003")#should not fall in above range
test_date2<-dmy("08-03-2005")#should fall in above range
test_date1 %within% forbidden_dates
[1] FALSE
test_date2 %within% forbidden_dates
[1] TRUE
>plot(my_dt)
my_dt<-my_dt[!(date_sample %within% forbidden_dates)]#applying the temporal cut
>plot(my_dt)