Home > Mobile >  Convert %B.%Y to date return NA in R
Convert %B.%Y to date return NA in R

Time:10-13

I have a dataframe which have one column with date content (the data type of this columns is char): 'November.2017', 'April.2017', etc.

I try to convert them with code below for testing:

strptime(c('November.2017', 'April.2017'), format='%B.%Y')
zoo::as.yearmon(c('November.2017', 'April.2017'), '%B.%Y')
as.Date(c('November.2017', 'April.2017'), format='%B.%Y')

Out:

[1] NA NA
[1] "Nov 2017" "Apr 2017"
[1] NA NA

As you can see, only zoo::as.yearmon works out, anyone could help to dig out why this happens? Thanks.

As far as I search, the issue seems raised by time-zone, I run Sys.setlocale('LC_TIME', 'English') on Rstudio, it's not working.

Updated:

strptime(c('November.01.2017', 'April.01.2017'), format='%B.%d.%Y')
as.Date('November.01.2017', format="%B.%d.%Y")

Out:

[1] "2017-11-01 CST" "2017-04-01 CST"
[1] "2017-11-01"

CodePudding user response:

An option is also parse_date

library(parsedate)
parse_date((c('November.2017', 'April.2017')))
[1] "2017-11-01 UTC" "2017-04-01 UTC"

The output is POSIXct class. It can be directly converted to Date class with as.Date

 as.Date(parse_date((c('November.2017', 'April.2017'))))
[1] "2017-11-01" "2017-04-01"
  • Related