0

I have a column of a data frame where some dates are formatted as

"2015-06-04"

and other dates as

"Thu Jun 04 15:12:10 2015"

Is there a way to match formatting and then add in a strptime()?

I tried using

for (i in 1:length(d1)){
  if((d1[i]) !=format("%Y-%m-%d")){
   d1[i]<- as.Date(strptime(d1[i], "%a %b %d %H:%M:%S %Y"))
  }
}

Where d1 is my list of dates.

C_Z_
  • 7,427
  • 5
  • 44
  • 81
GregdeLima
  • 404
  • 1
  • 9
  • 27
  • You could probably create an index using something like `grepl("[A-Za-z]", d1)` and then convert all of these dates to the desired format at once without any `for` loop. – David Arenburg Jun 04 '15 at 19:19
  • You may also check `lubridate::parse_date_time` and the `orders` arguments. See e.g. [here](http://stackoverflow.com/questions/25463523/convert-variable-with-mixed-date-formats-to-one-format-in-r/25463927#25463927) or [here](http://stackoverflow.com/questions/24551343/convert-many-formats-of-dates-to-one-standard-format-in-r/24551645#24551645) – Henrik Jun 04 '15 at 19:27
  • @DavidArenburg Still a bit new, and what you're suggesting gets me in the right direction, cause I'm getting the list of trues and falses. I'm just not making the connection between that and the if-then statement to actually do the replacing. Any tips? – GregdeLima Jun 04 '15 at 19:29
  • 1
    You don't need any if statement, all you need to do is `indx <- grepl("[A-Za-z]", d1) ; d1[indx] <- as.Date(strptime(d1[indx], "%a %b %d %H:%M:%S %Y"))`. – David Arenburg Jun 04 '15 at 19:32
  • What is the class of `d1`? – David Arenburg Jun 04 '15 at 19:37
  • Tried adding `d1[indx] <- as.Date(strptime(d1[indx==TRUE], "%a %b %d %H:%M:%S %Y"))` and that got `NA`s where applicable at least. – GregdeLima Jun 04 '15 at 19:37
  • 1
    Does `as.Date(strptime("Thu Jun 04 15:12:10 2015", "%a %b %d %H:%M:%S %Y"))` works on your system? – David Arenburg Jun 04 '15 at 19:38
  • 1)Class of d1 is currently showing as Factor w/ 10 Levels. 2) yes that works. Will try changing to strings. – GregdeLima Jun 04 '15 at 19:39
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/79691/discussion-between-gregdelima-and-david-arenburg). – GregdeLima Jun 04 '15 at 19:40

1 Answers1

0

@David Arenburg final solve here:

indx <- grepl("[A-Za-z]", d1) ; d1[indx] <- as.character(as.Date(strptime(d1[indx], format = "%a %b %d %H:%M:%S %Y")))

GregdeLima
  • 404
  • 1
  • 9
  • 27