Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using the between function in R

I have a dataframe with start and end dates in. I’m trying to work out if the dates I have fall on what row. For example my data frame is like so;

country startDate    endDate      weather
CHI     2022-12-29   2023-01-08    Rain
ENG     2023-01-01   2023-01-08    Cloud
GER     2023-01-02   2023-01-08    Cloud
FRA     2023-01-30   2023-02-05    Dry

I now want to create an indicator so i can see what country my set of dates refers to. So my list of dates is currently;

datestodo
2023-02-03
2023-02-04

So therefore I need what i am trying to write to return the row for FRA. I have tried to do this with the between argument but think im struggling/might not work as the start and end are not linked as they are in different columns

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my attempt

activedates = between(datestodo, mydf$startDate, mydf$endDate)

Doesn’t have to be done using the between function, a which is perfectly fine too or similar

>Solution :

We could use which() to identify the row indeces of the given dates that fall between the startDate and endDate columns.

with mydf[which…, ] we then subset the rows.

base R:

datestodo <- as.Date(c("2023-02-03", "2023-02-04"))

mydf[which(datestodo >= mydf$startDate & datestodo <= mydf$endDate), ]
  country  startDate    endDate weather
4     FRA 2023-01-30 2023-02-05     Dry
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading