-3

I don't know how to format the dates which are inserted as "7-1-2019" to "07-01-2019" can someone help me with that?

I was trying with this

[, rq_date_inserted1:= as.Date(rq_date_inserted1, "%d/%mm/%Y")]

but that's not working properly as after doing so some of the dates are not recognized;/

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • The `format` argument in `as.Date` accepts the **input** format, because it doesn't "know" how to guess it. Giving it `"%d/%mm/%Y"` doesn't make sense as this is neither your input nor desired format, so not sure what were you trying to do there. Please read `?strptime` documentation in order to understand formats in general. In either way, there is an `anytime` package that has some "guessing" mechanism that could be helpful for you if you don't want to mess around with formats. – David Arenburg Sep 25 '19 at 12:28

1 Answers1

0
format( as.Date( "7-1-2019", format = "%d-%m-%Y" ), "%d-%m-%Y" ) 

returns a string: [1] "07-01-2019"

If you expect a Date-object as output, use

as.Date( "7-1-2019", format = "%d-%m-%Y" )

which returns a Date: [1] "2019-01-07"

edit

based on comments below

dates <- c("8/28/2019","8/2/2019" ,"8/8/2019", "8/14/2019", "12/1/2019", "1/12/2019")

format( as.Date( dates, format = "%m/%d/%Y" ), format = "%d-%m-%Y" )

returns

 [1] "28-08-2019" "02-08-2019" "08-08-2019" "14-08-2019" "01-12-2019" "12-01-2019"
Wimpel
  • 26,031
  • 1
  • 20
  • 37
  • unfortunately applying that on the column where i have the dates gives me back the following " NA NA [953] NA NA NA NA NA "07-05-2019" "07-05-2019" "07-05-2019" [961] "08-12-2019" "08-12-2019" "08-12-2019" "08-12-2019" "09-04-2019" "09-04-2019" NA NA [969] NA NA "08-12-2019" "08-12-2019" "08-07-2019" "08-07-2019" "08-07-2019" NA – user11502831 Sep 25 '19 at 12:38
  • 2
    On the the NA-rows your data-column was (probably) not providing a expected formatted string to the as.Date function... see @DavidArenburg's comment above. – Wimpel Sep 25 '19 at 12:44
  • It is probably a good idea to edit some relevant sample data into your question. Read the top-answer here: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Wimpel Sep 25 '19 at 13:06
  • in the whole column, I have the following format: 8/28/2019,8/2/2019 ,8/8/2019, 8/14/2019 and the problem is that sometimes one has months 11 or 12 and sometimes 1.thats why the above solution cant work, so I don't want to go through each row of 1000000 data and change their format via above suggest a solution or at least I don't know how to do it fast. – user11502831 Sep 25 '19 at 13:07
  • 8/28/2019,8/2/2019 ,8/8/2019, 8/14/2019 looks like format "%m/%d/%Y"... have you tried that? – Wimpel Sep 25 '19 at 13:08