1

I have a data set of ~90,000 rows where individuals can have multiple enrollments in a program. For example;

id = c(1,1,3,3,5,5)
entry_date = c('2014-01-01', '2014-12-01', '2000-03-12', '2002-07-09', '2011-11-05','2016-12-01')
exit_date = c('2014-01-02', '2015-02-04', '2001-04-05', '2006-09-11', '2016-09-01', '2017-02-02')
test <- data.frame(id, entry_date, exit_date)
test


id entry_date   exit_date
1  2014-01-01  2014-01-02
1  2014-12-01  2015-02-04
3  2000-03-12  2001-04-05
3  2002-07-09  2006-09-11
5  2011-11-05  2016-09-01
5  2016-12-01  2017-02-02

I am attempting to subset anyone whose program duration (entry_date and exit_date) includes the whole or part of the year 2014. So based on the example data I would like to include the all the following rows;

id  entry_date    exit_date
1   2014-01-01   2014-01-02 
1   2014-12-01   2015-02-04
5   2011-11-05   2016-09-01

Thanks for any advice.

3 Answers 3

2

One way, I could think of is extracting year from entry_date and exit_date and then create a sequence between them using mapply and check if "2014" exists in that sequence and select those entries accordingly.

test[mapply(function(x, y) 2014 %in% seq(x,y) ,
 as.numeric(format(as.Date(test$entry_date), "%Y")), 
 as.numeric(format(as.Date(test$exit_date), "%Y"))), ]

#  id entry_date  exit_date
#1  1 2014-01-01 2014-01-02
#2  1 2014-12-01 2015-02-04
#5  5 2011-11-05 2016-09-01
1

I think you should've split entry_date and exit_date up into c(year,month,day) before you put them in a data frame. But anyway, using dplyr and tidyr:

library(dplyr)
library(tidyr)
test %>%
  separate(entry_date, c("entry_year","entry_month", "entry_day"), "-") %>%
  separate(exit_date, c("exit_year","exit_month","exit_day"),"-") %>%
  filter(entry_year <= 2014 & exit_year>=2014)

This gives:

  id entry_year entry_month entry_day exit_year exit_month exit_day
1  1       2014          01        01      2014         01       02
2  1       2014          12        01      2015         02       04
3  5       2011          11        05      2016         09       01
1

Although @RonakShah has provided a very smart solution to solve the problem. But since OP had mentioned about large data I thought to mention that lubridate and data.table combination can make it faster.

library(lubridate)
library(data.table)
setDT(test)

test[year(ymd(entry_date)) <= 2014 & year(ymd(exit_date)) >= 2014]
#   id entry_date  exit_date
#1:  1 2014-01-01 2014-01-02
#2:  1 2014-12-01 2015-02-04
#3:  5 2011-11-05 2016-09-01

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.