Trouble formatting Date

Hello,

I have a data frame with dates in a character vector that have the format mm/dd/yyyy. When I try to turn it into a date format using as.Date(), it turns all the years into the value "2020." Below is the original dataframe:

  Date       PO4_mg_L NH4_mg_L NO2_mg_L NO3F_mg_L NO23_mg_L CHL_A_ug_L
  <chr>         <dbl>    <dbl>    <dbl>     <dbl>     <dbl>      <dbl>
1 02/03/2015   0.0045   0.0695   0.034      0.502     0.536      NA   
2 03/02/2016   0.011    0.370    0.0245     0.708     0.733       7.6 
3 03/07/2018   0.007    0.174    0.018     NA         0.482       1.15
4 03/09/2017   0.0265  NA       NA         NA         0.599       5.9 
5 04/18/2016   0.01     0.083    0.021      0.204     0.225      22.2 
6 04/19/2016   0.01     0.109    0.0201     0.200     0.220      16.7 

Then I use the following code:

dfn1$Date <- as.Date(dfn1$Date, format="%m/%d/%y")

And it gives me this:

  Date       PO4_mg_L NH4_mg_L NO2_mg_L NO3F_mg_L NO23_mg_L CHL_A_ug_L
  <date>        <dbl>    <dbl>    <dbl>     <dbl>     <dbl>      <dbl>
1 2020-02-03   0.0045   0.0695   0.034      0.502     0.536      NA   
2 2020-03-02   0.011    0.370    0.0245     0.708     0.733       7.6 
3 2020-03-07   0.007    0.174    0.018     NA         0.482       1.15
4 2020-03-09   0.0265  NA       NA         NA         0.599       5.9 
5 2020-04-18   0.01     0.083    0.021      0.204     0.225      22.2 
6 2020-04-19   0.01     0.109    0.0201     0.200     0.220      16.7 

Can anyone figure out what I'm doing wrong? Why is it changing all the years to 2020?

Here is a snippet of my data:

structure(list(Date = structure(c(18295, 18323, 18328, 18330, 
18370, 18371), class = "Date"), PO4_mg_L = c(0.0045, 0.011, 0.007, 
0.0265, 0.01, 0.01), NH4_mg_L = c(0.0695, 0.3695, 0.1745, NA, 
0.083, 0.108857142857143), NO2_mg_L = c(0.034, 0.0245, 0.018, 
NA, 0.021, 0.0201428571428571), NO3F_mg_L = c(0.502, 0.7085, 
NA, NA, 0.203857142857143, 0.199714285714286), NO23_mg_L = c(0.536, 
0.733, 0.4815, 0.5995, 0.224857142857143, 0.219857142857143), 
    CHL_A_ug_L = c(NA, 7.6, 1.15, 5.9, 22.2285714285714, 16.7428571428571
    )), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))

Thanks so much for any help!!

Of course after I type all this out, I try format="%m/%d/%Y" and it works. GAH! Thanks anyway, I hope someone else has the same problem one day and this helps.

To make handling datetimes easier, you could investigate the lubridate package:

lubridate::mdy("02/03/2015")
#> [1] "2015-02-03"

Created on 2021-12-30 by the reprex package (v2.0.1)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.