0

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,

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.