1

When filter some days value from dataframe, I have to repeat 'as.Date' many times in filter condition sentence. Is there any way to simplify it? Thanks!

library(tidyverse)
test_data <- data.frame(mday=seq.Date(as.Date('2021-1-1'),
                        as.Date('2021-12-30'),by="1 day"),
                        value=rnorm(364))
# can't work
test_data %>% filter(mday %in% c(as.Date('2021-1-1','2021-7-1','2021-10-7')))

# can work, but have to repeat 'as.date' many times
test_data %>% filter(mday %in% c(as.Date('2021-1-1'),
                                 as.Date('2021-7-1'),
                                 as.Date('2021-10-7')))
zx8754
  • 52,746
  • 12
  • 114
  • 209
anderwyang
  • 1,801
  • 4
  • 18

1 Answers1

3

You are close. Should be:

test_data %>% filter(mday %in% as.Date(c('2021-1-1','2021-7-1','2021-10-7')))

It is because at first you need to create a vector, i.e. use c() function and then you can perform modifications on this vector, in your case - change vector to date.

gss
  • 1,334
  • 6
  • 11