Tamra.y
Tamra.y

Reputation: 245

as.Date conversion returns NA

I am using this data. When I want to define the variable as.Date() I am getting NA.

This is the code I am using. Can someone please advise what I am doing wrong?

dataf <- read.csv("DB.csv")
dataf$Date <- as.Date(dataf$Date, format = "%b-%Y")
str(dataf)
'data.frame':   55 obs. of  9 variables:
 $ Date     : Date, format: NA NA ...
 $ Sydney   : num  85.3 88.2 87 84.4 84.2 84.8 83.2 82.6 81.4 81.8 ...
 $ Melbourne: num  60.7 62.1 60.8 60.9 60.9 62.4 62.5 63.2 63.1 64 ...  
 $ Brisbane : num  64.2 69.4 70.7 71.7 71.2 72 72.6 73.3 73.6 75 ...
 $ Adelaide : num  62.2 63.9 64.8 65.9 67.1 68.6 68.6 69.3 70 71.6 ...  
 $ Perth    : num  48.3 50.6 52.5 53.7 54.7 57.1 59.4 62.6 65.2 70 ...
 $ Hobart   : num  61.2 66.5 68.7 71.8 72.3 74.6 75.8 76.9 76.7 79.1 ...
 $ Darwin   : num  40.5 43.3 45.5 45.2 46.8 49.7 53.6 54.7 56.1 60.2 ...
 $ Canberra : num  68.3 70.9 69.9 70.1 68.6 69.7 70.3 69.9 70.1 71.7 ...

Upvotes: 1

Views: 4084

Answers (1)

CPak
CPak

Reputation: 13581

In addition to the good suggestions in the comments, you should try lubridate::parse_date_time" which can handle incomplete dates

as.Date("01-2017", format="%m-%Y")
# [1] NA
as.POSIXct("01-2017", format="%m-%Y")
# [1] NA
as.POSIXlt("01-2017", format="%m-%Y")
# [1] NA

library(lubridate)
parse_date_time("01-2017", "my")
# [1] "2017-01-01 UTC"

Upvotes: 5

Related Questions