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;


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

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

Leave a Reply