I have a large dataframe and I want to select rows which satisfy condition on date columns. The dataframe is similar to this:
library(tidyverse)
library(lubridate)
curdate <- seq(as.Date("2000/1/1"), by = "month", length.out = 24)
expdate <- rep(seq(as.Date("2000/3/1"), by = "quarter", length.out = 12),2)
afactor <- rep(c("C","P"),12)
anumber <- runif(24)
df<-data.frame(curdate, expdate, afactor, anumber)
df$expdate[12]<-as.Date("2001-02-01")
I would like to get the rows which the expiration date (expdate) is two months later than the current date (curdate). First I used the following line for that:
df_select1 <- df %>% group_by(curdate, afactor) %>%
filter(month(expdate) == month(curdate)+2)
But it misses the cases when the month is November or December (for instance row 12 of df here). So I want to add a condition, to deal with these cases. I wrote:
df_select2 <- df %>% group_by(curdate, afactor) %>%
if_else(month(curdate)<11,
filter(month(expdate) == month(curdate)+2),
filter(month(expdate) == month(curdate)-10))
but I get the following error: condition must be a logical vector, not a grouped_df/tbl_df/tbl/data.frame object.
Aucun commentaire:
Enregistrer un commentaire