Reputation: 585
I have a bunch of dates:
dates
[1] "24/06/2010" NA NA NA "11/05/2005" NA "24/02/2006"
[8] NA NA NA "27/10/2008" "09/05/2009" NA NA
[15] "14/12/2008" "14/12/2008" NA "07/04/2009" NA
And wanna make a new vector where the dates are transformed into numbers and the NA transformed into -1 values. I know that in Excel dates are converted into numbers according to a standard procedure, here I don't know.
So for example if we fix as starting date 01/01/2008 as number 0 and count from there
24/06/2010 would be 905 days from the starting date.
Upvotes: 0
Views: 115
Reputation: 677
[Updated] Does this fit your question?
ifelse(is.na(dates),-1,as.Date(strptime(dates,'%d/%m/%Y'))-as.Date("2008-01-01"))
Upvotes: 0
Reputation: 81693
Here's an approach:
# the reference date
starting_date <- as.Date("2008-01-01")
# transform the character vector to a date vector and subtract the reference date
res <- as.Date(dates, "%d/%m/%Y") - starting_date
# replace NAs with -1
res[is.na(res)] <- -1
The result:
# Time differences in days
# [1] 905 -1 -1 -1 -965 -1 -676 -1 -1 -1 300 494 -1 -1 348
# [16] 348 -1 462 -1
Upvotes: 3