2

I am trying to convert charater string to date class value with as.Date function. The character string that I’m working on looks like below:

[1] "Sep 1, 2016"  "Aug 31, 2016" "Aug 30, 2016" "Aug 29, 2016" "Aug 26, 2016"
[6] "Aug 25, 2016" "Aug 24, 2016" "Aug 23, 2016" "Aug 22, 2016" "Aug 19, 2016"
[11] "Aug 18, 2016" "Aug 17, 2016" "Aug 16, 2016" "Aug 12, 2016" "Aug 11, 2016"
[16] "Aug 10, 2016" "Aug 9, 2016"  "Aug 8, 2016"  "Aug 5, 2016"  "Aug 4, 2016"
[21] "Aug 3, 2016"  "Aug 2, 2016"  "Aug 1, 2016"  "Jul 29, 2016" "Jul 28, 2016"
[26] "Jul 27, 2016" "Jul 26, 2016" "Jul 25, 2016" "Jul 22, 2016" "Jul 21, 2016"
[31] "Jul 20, 2016" "Jul 19, 2016" "Jul 18, 2016" "Jul 15, 2016" "Jul 14, 2016"
[36] "Jul 13, 2016" "Jul 12, 2016" "Jul 11, 2016" "Jul 8, 2016"  "Jul 7, 2016"

I tried the two different codes for this problem, but It just yields NA.

as.Date("Sep 1, 2016",format="%b %d, %Y") #approach1
as.Date(gsub(",","","Sep 1, 2016"),format="%b %d %Y") #approach2
  1. What is the problem with the code that I have tried?
  2. What is a proper code for this conversion problem?

Thanks in advance.

Jaap
  • 81,064
  • 34
  • 182
  • 193
송병채
  • 21
  • 2

2 Answers2

2

I guess the problem is your current locale

Try to temp. set it to the C locale like so

lct <- Sys.getlocale("LC_TIME"); 
Sys.setlocale("LC_TIME", "C")
as.Date("Sep 1, 2016",format="%b %d, %Y") #approach1
Sys.setlocale("LC_TIME", lct)  

See this question + answer for further details

Community
  • 1
  • 1
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
0

Another possibility is the use of the R-package lubridate.

install.packages("lubridate")

lubridate::mdy("Sep 1, 2016")

# [1] "2016-09-01"

The function mdy is used, because the first input is the month "m", the second is the day "d" and the third one is the year "y".

J_F
  • 9,956
  • 2
  • 31
  • 55