-2

I'm trying to create a dummy variable for specific dates (covid effect)

When using the code below, got only NA's in the column.

df$dummy <- ifelse(df$date > as.Date("2018-01-01", format = "%Y/%m/%d") &
                               df$date < as.Date("2020-06-15", format = "%Y/%m/%d"), 1, 0)

Does anyone know how to fix it?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Hi @Alexvitoria, can you put head(df$date) of your data in code. also please put four spaces before df$dummy.. line to convert it into code format. – Harshal Gajare Jul 14 '20 at 16:36
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 14 '20 at 16:40
  • thanks guys, I sorted it out! – alexvitoria Jul 14 '20 at 16:42

1 Answers1

1
as.Date("2018-01-01", format = "%Y/%m/%d")

will return NA, use one of these:

as.Date("2018/01/01", format = "%Y/%m/%d")
as.Date("2018-01-01", format = "%Y-%m-%d")

Might I also add that dplyr is a great package for working with tables, the result might look like this:

library(dplyr)
df <- df %>% 
     mutate(Dummy = ifelse(date > as.Date("2018/01/01", format = "%Y/%m/%d") & date < as.Date("2020/06/15", format = "%Y/%m/%d"), 1, 0))

Finally, it's always helpfull to add a reproducible example, simply adding

df <- data.frame(date = as.Date(c("2018/05/01", "2018/01/01"), format = "%Y/%m/%d"))

will make answering the question easier

dspn
  • 314
  • 2
  • 9