-1

So I've got a data frame that looks something like this,

         Date        Age_group
1     01-06-2021        <17
2     01-06-2021       17-59
3     01-06-2021        >60 
4     02-06-2021        <17
5     02-06-2021       17-59
6     02-06-2021        >60
7     03-06-2021        <17
8     03-06-2021       17-59
9     03-06-2021        >60

and goes on a long way. And I need every date converted to yyyy-mm-dd. I've tried

as.Date("01/06/2021", format="%d/%m/%Y")

But obviously that just changed them all to that exact date in said format. Bare with me I'm very new to r, any help would be really appreciated

Jeremiah
  • 5
  • 1

3 Answers3

0

You're probably looking for format:

my_date <- as.Date("31-12-2020", format = "%d-%m-%Y")

format(my_date, "%Y-%m-%d")
# [1] "2020-12-31"
heds1
  • 3,203
  • 2
  • 17
  • 32
0

Do this in 2 steps. First, use as.Date to convert your text dates to bona fide R dates. Then use format to convert back to text, in the format you want.

dates <- as.Date(df$Date, format="%d-%m-%Y")
df$Date <- format(dates, "%Y-%m-%d")
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You can do it like this:

df$Date <- as.Date(Date, format = "%d-%m-%Y")

Where "df" is the name of your dataframe.

koolmees
  • 2,725
  • 9
  • 23