Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Date formats in R [closed]

Tags:

date

r

dates <- as.Date(dli$Dates)

class(dates)
[1] "Date"

dates
   [1] "2016-01-01" "2016-01-02" "2016-01-03" "2016-01-04" "2016-01-05" "2016-01-06"
   [7] "2016-01-07" "2016-01-08" "2016-01-09" "2016-01-10" "2016-01-11" "2016-01-12"
  [13] "2016-01-13" "2016-01-14" "2016-01-15" "2016-01-16" "2016-01-17" "2016-01-18"
  [19] "2016-01-19" "2016-01-20" "2016-01-21" "2016-01-22" "2016-01-23" "2016-01-24"
  [25] "2016-01-25" "2016-01-26" "2016-01-27" "2016-01-28" "2016-01-29" "2016-01-30"
  [31] "2016-01-31" "2016-02-01" "2016-02-02" "2016-02-03" "2016-02-04" "2016-02-05"
  [37] "2016-02-06" "2016-02-07" "2016-02-08" "2016-02-09" "2016-02-10" "2016-02-11"

This is my date format , so i need to convert it into "2016-month-day" I am getting NA values

dates <- as.Date(dli$Dates,"%d/%b/%Y")

class(dates)
[1] "Date"

dates
   [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
  [31] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
  [61] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
  [91] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
 [121] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 

can you give any suggestions Thanks in Advance

like image 678
Eswar Avatar asked Dec 05 '25 04:12

Eswar


1 Answers

Good practice is to store date in R as YYYY-MM-DD, and your strings already seem to be at the good format, but :

The format you're passing to as.Date must describe what the strings contain, not what you're expecting as an output.

"%d/%b/%Y" stands for "day as a number (0-31) slash abbreviated month slash 4-digit year", and your strings format are "4-digit year - month as a number - day as a number".

If you want to format the date, you need to call format :

> date <- "2016-01-01"
> date <- as.Date(date, format = "%Y-%m-%d")
> date
[1] "2016-01-01"
> format(date, "%d/%b/%Y")
[1] "01/jan/2016"
like image 91
Colin FAY Avatar answered Dec 07 '25 18:12

Colin FAY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!