Home > Back-end >  R Using ifelse inside dplyr filter
R Using ifelse inside dplyr filter

Time:11-16

In my chart I would like to show data from previous month depending on what month we currently have. I have developed following piece of code for this purpose:

data %>% 
  mutate(mesic = month(create_date)) %>% 
  filter(ifelse(month(now()) > 1, mesic == month(now()) - 1, mesic == month(now())   11))

But the filter somehow does not apply (I end up with empty dataset). Is it not possible to use ifelse inside the filter?

CodePudding user response:

Solution to the problem is to use case_when instead of ifelse (credits to @Julian):

data %>%
  mutate(mesic = month(create_date)) %>%
  filter(
    case_when(
      month(now()) > 1 ~ mesic == month(now()) - 1,
      month(now()) == 1 ~ mesic == month(now())   11
    )
  )
  • Related