I have a dataset in which one column represents monthly Date:from 02/01/2004 to 09/01/2008, i have to create a dummy for the Dates in 2008. I tried to use:
dummy <- as.numeric(Date >= 01/01/2008)
,
but R said me that:
">= is not meaningful for factors"
hence i tried to transform the factor variable Date in a numeric one, but all my Dates disappeared, substituted with some random numbers.
This creates some data:
dat <- data.frame(
date = c("01/01/2017", "02/01/2017", "01/01/2018")
)
Now first we get the correct date format, then we create the dummy:
dat$date <- strptime(as.character(dat$date), "%d/%m/%Y") # correct date format
dat$date <- format(dat$date, "%Y-%m-%d") # change to Date variable
# create dummy:
dat$dummy <- 0
dat$dummy[which(dat$date >= "2018-01-01")] <- 1
Output:
date dummy
1 2017-01-01 0
2 2017-01-02 0
3 2018-01-01 1