Home > Mobile >  Turn date column into days from beginning integer Rstudio
Turn date column into days from beginning integer Rstudio

Time:10-21

Hi everyone so I am currently plotting time series graphs in Rstudio, I have created a nice time series graph however I would actually like the x axis not to be showing me the date but more like an integer showing a number from the starting date of the graph. Time Series Graph

Such as instead of seeing 01/01/2021 I want to see day 100, as in its the 100th day of recording data.

Do i need to create another column converting all the days into a numerical value then plot this? If so how do i do this. At the moment all i have is a Date column and the value i am plotting column. Column Data

Thanks

CodePudding user response:

Assuming you want 01/01/2021 as first day you could use that as a reference and calculate the number of days passed since the first day of recording and plot that, this should give you more like an integer showing a number from the starting date.

Not sure what your data frame looks like so hopefully this helps.

Using lubridate

  library(lubridate)

df

       Date
1 01/01/2021
2 02/01/2021
3 03/01/2021
4 04/01/2021

df$days <- yday(dmy(df$Date)) -1

Output:

        Date days
1 01/01/2021    0
2 02/01/2021    1
3 03/01/2021    2
4 04/01/2021    3

Which is indeed a numeric

str(df$days)
 num [1:4] 0 1 2 3

CodePudding user response:

This a simulation of dates

date.simulation = as.Date(1:100, "2001-01-01")

factor(date.simulation-min(date.simulation))

You just subtract the dates to the minimum date. And you need it as a factor for plotting purposes.

  •  Tags:  
  • r
  • Related