0

I am working with data containing the date column, and I want to change the date column of the dataset from character to the dates class. however, I couldn't do it as every time I get an error. I tried to do it by using the Lubridate package's function such ymd (), the base R function as.Dates() but in vain. can anyone help me to find out the error? here is what my data looks like and what I tried: Thank you in advance.

**head(my_data)
  X    *date week   weekday fatals
1 1 8/27/17   35    Sunday      4
2 2 8/28/17   35    Monday      5
3 3 8/29/17   35   Tuesday      6
4 4 8/30/17   35 Wednesday      6
5 5 8/31/17   35  Thursday      6
6 6  9/1/17   35    Friday      9***

> ***str(my_data)
'data.frame':   28 obs. of  5 variables:
 $ X      : int  1 2 3 4 5 6 7 8 9 10 ...
 $ date   : chr  "8/27/17" "8/28/17" "8/29/17" "8/30/17" ...
 $ week   : int  35 35 35 35 35 35 35 36 36 36 ...
 $ weekday: chr  "Sunday" "Monday" "Tuesday" "Wednesday" ...
 $ fatals : int  4 5 6 6 6 9 8 15 7 8 ...***

***

> as.Date(my_data$date, format= "%m%,%d%, %y%")  [1] NA NA NA NA NA NA
> NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

***

***> mdy(my_data$date)  
[1] "2017-08-27" "2017-08-28" "2017-08-29"
> "2017-08-30" "2017-08-31" "2017-09-01" "2017-09-02" "2017-09-03"
> "2017-09-04" [10] "2017-09-05" "2017-09-06" "2017-09-07" "2017-09-08"
> "2017-09-09" "2017-09-10" "2017-09-11" "2017-09-12" "2017-09-13" [19]
> "2017-09-14" "2017-09-15" "2017-09-16" "2017-09-17" "2017-09-18"
> "2017-09-19" "2017-09-20" "2017-09-21" "2017-09-22" [28] "2017-09-23"***
***
class(my_data$date) 
[1] "character"***
Humble
  • 11
  • 3

1 Answers1

0

You just need to make some small adjustment to the delimiters of your format string. Also, you only need to use % once per character. Maybe have a look at ?strptime for more information.

x <- "8/27/17"

y <- as.Date(x, format = "%m/%d/%y")
y
#> [1] "2017-08-27"

class(y)
#> [1] "Date"

Created on 2022-10-15 with reprex v2.0.2

dimfalk
  • 853
  • 1
  • 5
  • 15
  • Thank you @ falk-env, by using the recommendation you provided as. Date () I was able to bypass NAs but I got also a character. – Humble Oct 15 '22 at 10:03
  • Did you overwrite your existing `my_data$date` containing strings with the output from `as.Date(my_data$date, format = "%m/%d/%y")`? – dimfalk Oct 15 '22 at 10:18
  • yes that is what I did but when I check the class of the output, it was a character. – Humble Oct 15 '22 at 10:27