I have a df like this:
x <- data.frame("date1" = c("2018-09-12","2018-09-18", "2019-06-23"), "date2" = c("2018-09-10","2018-09-13","2018-12-12"))
> x
date1 date2
1 2018-09-12 2018-09-10
2 2018-09-18 2018-09-13
3 2019-06-23 2018-12-12
Now I would do an unique
on date1 which will result in unique date value. I would then create a new column and assign value of period to it based on date in col date2, like this
date1 date2 period
1 2018-09-12 2018-09-10 0
2 2018-09-18 2018-09-13 1 (as period 1: is 2018-09-12 to 2018-09-18 and date2 lies in it)
3 2019-06-23 2018-12-12 2 (as period 2: is 2018-09-18 to 2019-06-23 and date2 lies in that)
Is there is a way to do it in a vector form in R. Thanks
Can you try this?
periods = as.Date(sort(unique(x$date1)))
x$period = apply(as.data.frame(x$date2), 1, function(x){
findInterval(as.Date(x), periods)
})
You can use dates in date1
to find intervals in date2
findInterval(x$date2, x$date1)
#[1] 0 1 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.