Bob
Bob

Reputation: 35

Specify time periods for multiple years

I have a data set with a variable "date", from 2001-01-01 to 2015-12-31. I need to generate a new variable to indicate different time periods.

Time interval: Jan 15 to Feb 10.

Jan 15 to Feb 10, 2015 -- Time = 1

Jan 15 to Feb 10, 2001-2014 -- Time = 0

Is there a good method to generate the new variable?

Thanks a lot!

Upvotes: 0

Views: 48

Answers (1)

SmitM
SmitM

Reputation: 1376

If your date variable is not already a date time object, you can convert it using the as.Date() function like this:

df$Date <- as.Date(df$Date, format = "%Y-%m-%d")

The you can use an ifelse statement to create a new variable like this:

df$Time <- ifelse(df$Date > "2015-01-15" & df$Date < "2015-02-10", 1, 
ifelse((df$Date > "2014-01-15" & df$Date < "2014-02-10") | 
(df$Date > "2013-01-15" & df$Date < "2013-02-10") | 
(df$Date > "2012-01-15" & df$Date < "2012-02-10") | 
(df$Date > "2011-01-15" & df$Date < "2011-02-10"), 0, "NA"))

Upvotes: 1

Related Questions