Reputation: 1746
I'm trying to create a new var "PERIOD" based on dates. The sample data is given below:
Date
1/10/2012
1/11/2012
1/12/2012
1/13/2012
1/14/2012
1/15/2012
1/16/2012
1/17/2012
1/18/2012
After conditioning the new dataset looks like:
Date PERIOD
1/10/2012 Y1
1/11/2012 Y1
1/12/2012 Y1
1/13/2012 Y1
1/14/2012 Y1
1/15/2012 Y2
1/16/2012 Y2
1/17/2012 Y2
1/18/2012 Y2
The code I was using is
dat$PERIOD<-{If '1/10/2012' <= as.Date(dat$Date) <= '1/14/2012' dat$PERIOD='Y1' else
If '1/15/2012' <= as.Date(dat$Date) <= '1/18/2012'dat$PERIOD='Y2'
}
But I'm getting error:
Error: unexpected string constant in dat$PERIOD<-{If '1/10/2012'
Thank you. Regards,
Upvotes: 0
Views: 138
Reputation: 25736
Please see ?as.Date
for correct date format.
Your conditional statement is mostly wrong. R is case sensitive. You have to use if
. Please find some example code below:
d <- data.frame(Date=as.Date(paste(2012, 1, 10:18, sep="/")), stringsAsFactors=FALSE)
d$PERIOD <- ifelse(as.Date("2012/1/15") > d$Date, "Y1", "Y2")
Upvotes: 2