-1

I am trying to separate date from one column and trying to put the date in another column but the new column is horribly wrong when I compare the dates in both columns. I am attaching pic below. I am separating date from the started_at column and storing it in the date column.

The code I tried is in the image. For example in the 1st date in the started_at column is "4/1/2019" but when i separated it in a new column then it is returning "0004-01-20".

I have tried using format() as well as as.Date() but it is also not giving the same value as in parent column started_at. Picture is attached below.

zephryl
  • 14,633
  • 3
  • 11
  • 30
  • 1
    `as.Date("4/1/2019", format="%d/%m/%Y")` – Andre Wildberg Feb 25 '23 at 11:56
  • Hi Ahmad, welcome to stack overflow. Please provide data in a copy-pasteable format, eg by using `dput()`, [not as an image](https://meta.stackoverflow.com/a/285557/17303805). Also have a look at [How to make a great R reproducible example](https://stackoverflow.com/q/5963269/17303805). Thanks! – zephryl Feb 25 '23 at 14:49
  • Please provide enough code so others can better understand or reproduce the problem. – Community Feb 25 '23 at 22:52
  • I have found the solution. SOLUTION: all_trips$Date <- format(as.Date(all_trips$started_at, format = "%d/%m/%Y"), "%Y-%m-%d") We had to tell the as.Date function our current date is in which format and that's it. – Ahmad Nawaz Feb 25 '23 at 23:28

1 Answers1

0

I'm not sure why the format is not working, but as string variable, you could just:

stringsplit(all_trips$started_at, " " )

Or with tidyr:

all_trips <- tidyr::separate(all_trips, started_at, c("date", "hour"), sep = " ")

In stringr:

all_trips[c("date", "hour")] <- str_split_fixed(all_trips$started_at," ", 2) 
Ignacio2424
  • 116
  • 6
  • I have found the solution. SOLUTION: all_trips$Date <- format(as.Date(all_trips$started_at, format = "%d/%m/%Y"), "%Y-%m-%d") We had to tell the as.Date function our current date is in which format and that's it. – Ahmad Nawaz Feb 25 '23 at 23:26