2

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"
ah bon
  • 9,293
  • 12
  • 65
  • 148
  • 2
    It might be that converting to date expects a day, which you don't have. Converting to year-month doesn't, so it works okay – camille Oct 12 '21 at 16:11
  • Based on the link, I use `as.Date(paste('November.2017', '-01', sep=''), format = '%B.%Y-%d')`, it returns NA as well. – ah bon Oct 12 '21 at 16:22
  • 1
    For a date to be valid in standard formats, it needs to have a day associated with it. `as.yearmon` makes the assumption that day should always be the first of the month, while `as.Date` fails rather than "invent" the day. If you want to use `as.Date` you should add the day to your strings: `c('November.2017', 'April.2017') %>% gsub("\\.", "\\.01\\.", .) %>% as.Date(., "%B.%d.%Y")` – Mako212 Oct 12 '21 at 16:27
  • Your code with `paste` works fine for me. If it matters (dates can be OS dependent) I'm on macOS – camille Oct 12 '21 at 17:32

1 Answers1

2

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"
akrun
  • 874,273
  • 37
  • 540
  • 662