Search code examples
rdatetimetime-serieslubridate

How to generate a time series vector(2001/01, 2001/02,.....)?


I have a 240 rows data(temperature from 2001.01 to 2020.12).

I want to generate a vector just like

c(2001/01, 2001/02,...2001/12,2002/01,......2020/12)

to plot a time series figure.

library(tidyverse)
df <- tibble(tem= runif(240,1,10),
             time=1:240)
ggplot(df,aes(time,tem))+
  geom_line()+
  geom_point()+
  theme_bw()

enter image description here

How can I do it in R?


Solution

  • Using ym from lubridate. Note that the output in your desired format is a string. dates are internally always stored in a standardized format (numerical), e.g. "2023-01-01 12:12:12", corresponding to %Y-%m-%d %H:%M:%S

    library(lubridate)
    
    begin <- "2001/01"
    
    end <- "2001/04"
    
    format(seq.Date(ym(begin), ym(end), "month"), "%Y/%m")
    [1] "2001/01" "2001/02" "2001/03" "2001/04"
    

    If you want a time series object of class ts

    begin <- c(2001, 1)
    
    end <- c(2001, 4)
    
    ts(1:4, start = begin, end = end, frequency = 12)
         Jan Feb Mar Apr
    2001   1   2   3   4
    

    EDIT: The edit changes the answer significantly (almost worthy a different answer), still add it here. Basically just add a date object and do the format in ggplot2 with scale_x_date.

    library(dplyr)
    library(lubridate)
    library(ggplot2)
    
    set.seed(42)
    
    begin <- "2001/01"
    
    end <- "2001/10"
    
    df <- tibble(tem = runif(10, 1, 10), 
                 time = seq.Date(ym(begin), ym(end), "month"))
    
    ggplot(df, aes(time, tem)) + 
      geom_line() + 
      geom_point() + 
      theme_bw() + 
      scale_x_date(date_labels = "%Y/%m", date_breaks = "1 month")
    

    line plot