2
votes

I have dates in a character vector. I cannot easily convert to a date vector using as.Date, because not all of the strings have the form mm/dd/yyyy, thus giving me the ambiguous date error. Some strings have the form m/dd/yyyy (months 1:9).

Here's part of the vector:

data$Date <- c("8/26/2014","3/10/2014","9/25/2014","11/12/2014","8/4/2015")

Indicator for date to let me know which strings I need to add a zero to

data$date <- grepl("[0-9]{2}/[0-9]{2}/[0-9]{4}", data$Date)

Attempt to add zeros through a conditional:

data$Date<-ifelse(data$date == "FALSE", paste0("0", data$Date), data$Date)

Doesn't work (I'm not familiar with paste). Any concise solutions to add a leading zero to single digit months (m/dd/yyy)? I'm guessing gsub or sub? I need all the strings to be in form mm/dd/yyy so I can convert to a date vector.

1
Padding with a leading zero is unnecessary here, but for future reference, here's one option: data$Date = ifelse(grepl('^[1-9]/', Date), paste0("0", data$Date), data$Date) - eipi10
Thanks that worked. What do you mean it's not necessary? There's a way R can recognize it as a date without adding the zero? - J. Collins
Yes, see @Florian's answer below. You just have to provide a format string that tells asDate how to parse your date strings. - eipi10

1 Answers

1
votes
data <- data.frame(Date=c("8/26/2014","3/10/2014","9/25/2014","11/12/2014","8/4/2015"))

as.Date(data$Date,format="%m/%d/%Y") 

works fine for me with your data. Output is

"2014-08-26" "2014-03-10" "2014-09-25" "2014-11-12" "2015-08-04"