2
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

r2evans
  • 141,215
  • 6
  • 77
  • 149
lytto
  • 23
  • 3
  • That is because the last two rows are not of order `%m-%d-%y` – Onyambu Jun 05 '22 at 14:48
  • 1
    Take a look at `anytime`, which is more flexible. – mhovd Jun 05 '22 at 15:43
  • If your data only varies on the use of `-` versus `/`, then I suggest that onyambu's answer is the clearest. Otherwise, if it can vary in other ways (e.g., m-d-y vs d-m-y), then this is a duplicate, where https://stackoverflow.com/a/52319606/3358272 provides resolution – r2evans Jun 05 '22 at 15:58

2 Answers2

3
 as.Date.character(gsub("/", "-",td3$date), '%m-%d-%Y')
[1] "2016-05-06" "2016-05-07" "2016-04-13" "2016-04-14"
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

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"
TarJae
  • 72,363
  • 6
  • 19
  • 66