Search code examples
rdatedate-conversion

Why are NAs introduced when I convert character dates to date format?


I have some dates:

      [,1]           
 [1,] "March 4 2018" 
 [2,] "March 11 2018"
 [3,] "March 18 2018"
 [4,] "March 26 2018"
 [5,] "April 2 2018" 
 [6,] "April 9 2018" 
 [7,] "April 16 2018"
 [8,] "April 23 2018"
 [9,] "April 30 2018"
[10,] "March 4 2018" 
[11,] "March 11 2018"
[12,] "March 18 2018"
[13,] "March 26 2018"
[14,] "April 2 2018" 
[15,] "April 9 2018" 
[16,] "April 16 2018"
[17,] "April 23 2018"
[18,] "April 30 2018"

I want to convert these to date format (using anytime) but it results in some NA values:

[1] NA                        "2018-03-11 01:00:00 GMT" "2018-03-18 01:00:00 GMT" "2018-03-26 01:00:00 BST" NA                       
 [6] NA                        "2018-04-16 01:00:00 BST" "2018-04-23 01:00:00 BST" "2018-04-30 01:00:00 BST" NA                       
[11] "2018-03-11 01:00:00 GMT" "2018-03-18 01:00:00 GMT" "2018-03-26 01:00:00 BST" NA                        NA                       
[16] "2018-04-16 01:00:00 BST" "2018-04-23 01:00:00 BST" "2018-04-30 01:00:00 BST"

This is the command I used:

library(anytime)
anytime(df$date)

Why is this happening and how do I rectify it?


Solution

  • Following people's suggestions, as.POSIXct(df$date, format='%B %d %Y') has worked for me here.

    Thank you all.