lytto
lytto

Reputation: 23

Converting a date in R returns NA

date
05-06-2016
05-07-2016
4/13/2016
4/14/2016

I want to format the column to date format using below code

td3 <- read.csv("Book2.csv")
td3$date <- as.Date(td3$date, "%m-%d-%y")

when i run the code the last 2 rows return NA

Upvotes: 2

Views: 535

Answers (2)

TarJae
TarJae

Reputation: 78927

Here is a solution with parse_date_time from lubridate package:

library(lubridate)
as.Date(parse_date_time(df$date, orders = c('mdy', 'dmy')))

[1] "2016-05-06" "2016-05-07" "2016-04-13" "2016-04-14"

Upvotes: 0

Onyambu
Onyambu

Reputation: 79208

 as.Date.character(gsub("/", "-",td3$date), '%m-%d-%Y')
[1] "2016-05-06" "2016-05-07" "2016-04-13" "2016-04-14"

Upvotes: 3

Related Questions