Home > Blockchain >  How to convert date day per day in R into date month per month in numeric format
How to convert date day per day in R into date month per month in numeric format

Time:12-24

I have a lot of dates on R, for example :

18/03/2020
19/03/2020
20/03/2020
21/03/2020
      .
      .
01/04/2020
02/04/2020
03/04/2020
04/04/2020

And I have date from 18/03/2020 into 09/11/2021

My aim is to do a PCA on R. Then, I would like to transform all these date into numeric to use it.

I would like to have month per month and not day per day.

For example :

202003
202004
202005
.
.
.
202111

I need to have my individu as numeric to use function PCA

Thanks for reading me

CodePudding user response:

You can convert dates with the format() function.

> Sys.Date()  # origin Date
[1] "2021-12-23"
> format(Sys.Date(), "%Y%m") # date in YYYYMM
[1] "202112"

Update:

As you need it as numeric

as.numeric(format(Sys.Date(), "%Y%m"))

CodePudding user response:

If the format is in %d/%m/%Y, we may convert to Date class first and then do the formatting

format(as.Date(df1$date, "%d/%m/%Y"), "%Y%m")

Or another option is a regex

sub("^../(..)/(....)", "\\2\\1", df1$date)
  • Related