# R: Date Calculation

#### Cynderella

##### New Member
Let I have some data against time :

Code:
    time <- seq(ISOdate(2007,7,1,0), ISOdate(2008,4,5,23), by = "1 hour")
y <- rnorm(n = length(time))

dat <- data.frame(time = time, y = y)
Now I am trying to create another variable day_index which will take value 1 for 2007-07-01 irrespective of hours (that is first 24 values of day_index will be 1 since there are 24 hours in a day);
then "day_index=2" if the date is 2007-07-02;

"day_index=32" if the date is 2007-08-01;

"day_index=279" if the date is 2008-04-05.

How can I do that?

#### helicon

##### Member
You could use cut to convert the variable to a factor based on days and then change that to a numeric variable, like so:

Code:
dat$day_index <- as.numeric(cut(dat$time, "days"))
Or if the dates are not continuous in your real dataset you could try:

Code:
dat$day_index <- trunc(difftime(dat$time, ISOdate(2007,7,1,0),units="days")) + 1

Last edited:

#### Cynderella

##### New Member
You could use cut to convert the variable to a factor based on days and then change that to a numeric variable, like so:

Code:
dat$day_index <- as.numeric(cut(dat$time, "days"))
Or if the dates are not continuous in your real dataset you could try:

Code:
dat$day_index <- trunc(difftime(dat$time, ISOdate(2007,7,1,0),units="days")) + 1
Excellent. Thank you very much for your cooperation.

Best Regards,
Cynderella.