我有以下带有日期的数据框。
ID start_date end_date Intrvl a_date b_date c_date
1 2013-12-01 2014-05-01 2013-12-01--2014-05-01 2014-01-01 2014-03-10 2015-03-10
2 2016-01-01 2016-07-01 2016-01-01--2016-07-01 2014-02-01 NA 2016-02-01
3 2014-01-01 2014-07-01 2014-01-01--2014-07-01 2014-02-01 2016-02-01 2014-07-01
我想知道,
如果来自a_date,b_date和c_date列的日期在我使用lubridate :: interval(start_date,end_date)计算的间隔期内。实际上,我有一个包含400列的数据框。
日期列的名称(如果日期在相应的间隔内)。像下面的输出
ID Within_Intrvl
1 a_b
2 a
3 a_c
我已阅读此问题的答案[link],但没有帮助我。谢谢!
假设您的数据已经使用lubridate进行了转换,
input<- df %>%
mutate(start_date=ymd(start_date)) %>%
mutate(end_date=ymd(end_date)) %>%
mutate(a_date=ymd(a_date)) %>%
mutate(b_date=ymd(b_date)) %>%
mutate(c_date=ymd(c_date)) %>%
mutate(Intrvl=interval(start_date, end_date))
您可以在lubridate中使用%within%运算符
result <- input %>%
mutate(AinIntrvl=if_else(a_date %within% Intrvl,"a","")) %>%
mutate(BinIntrvl=if_else(b_date %within% Intrvl,"b","")) %>%
mutate(CinIntrvl=if_else(c_date %within% Intrvl,"c","")) %>%
mutate(Within_Intrvl=paste(AinIntrvl,BinIntrvl,CinIntrvl,sep="_")) %>%
select(-start_date,-end_date,-Intrvl,-a_date,-b_date,-c_date )
您可以根据自己的喜好设置“ Interior_Intrvl”列的格式,并确定要如何处理NA
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句