Assuming you want to count January 1 of the year as 0, we get:
DF <- data.frame(Date = c("02/01/2000", "20/02/2000", "12/12/2000", "13/01/2001")) DF$Date <- as.Date(DF$Date, "%d/%m/%Y") Diff <- function(x, start) as.numeric(x - as.Date(cut(start, "year"))) transform(DF, NumDays = Diff(Date, Date), TotalDays = Diff(Date, Date[1]))
which gives:
Date NumDays TotalDays 1 2000-01-02 1 1 2 2000-02-20 50 50 3 2000-12-12 346 346 4 2001-01-13 12 378
If you want to read on January 1 1, then add 1 to the expression in Diff .
UPDATE: Correction.
UPDATE: Added DF definition to make it standalone.
UPDATE: we add a run using the data in the comment below.
> DF <- data.frame(Date = as.Date(c("1980-01-03", "1980-01-04", "1980-01-05", + "1980-01-07", "1980-01-10", "1980-01-16"))) > > Diff <- function(x, start) as.numeric(x - as.Date(cut(start, "year"))) > transform(DF, NumDays = Diff(Date, Date), TotalDays = Diff(Date, Date[1])) Date NumDays TotalDays 1 1980-01-03 2 2 2 1980-01-04 3 3 3 1980-01-05 4 4 4 1980-01-07 6 6 5 1980-01-10 9 9 6 1980-01-16 15 15
source share