简体   繁体   中英

Convert R date from 1/1/2016 to 01/01/2016

I have found multiple posts that go from 01/01/2016 to 1/1/2016. I would like to go the other way.

Here is my data set

Date    duration   flavor    newDate 
6/4/2016    38  amd64chk    4/6/2016
6/3/2016    873 amd64chk    3/6/2016
6/3/2016    173 amd64chk    3/6/2016
6/3/2016    3383    amd64chk    3/6/2016
6/1/2016    665 amd64chk    1/6/2016
5/26/2016   665 amd64chk    NA
5/25/2016   665 amd64chk    NA
5/24/2016   147 amd64chk    NA
5/24/2016   733 amd64chk    NA
5/24/2016   249 amd64chk    NA

There are two issues here:

  1. The date is only converted when the date is in 1/1/2016 format, once the length increases my code stops working

  2. the type of each column is different. Date is "factor" and newDate is "POSIXt"

Code

df_amd64chk$newDate <- strptime(as.character(df_amd64chk$Date), "%d/%m/%Y")

I am rather new to R, so my apologies if this isn't well stated. Thanks in advance.

The code you provided is almost correct. You may want to try this small modification:

df_amd64chk$newDate <- as.Date(df_amd64chk$Date,"%m/%d/%Y")

Note that the order of %m and %d is reversed with respect to the code posted in the OP.

If you aren't interested in preserving a Date class, you can convert the output in a character string with another format:

df_amd64chk$newDate <- format(as.Date(df_amd64chk$Date,"%m/%d/%Y"),"%m/%d/%Y")

This will restore almost the original format, but it will add leading zeros where the month or the day have only one digit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM