Coerce xts to ts in R

后端 未结 5 1804
Happy的楠姐
Happy的楠姐 2021-01-07 02:54

I have xts time-series object for 10 days of data. The data is sampled at minutes frequency. Therefore, for each day, I have 1440 observations. I need to coerce

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-07 03:34

    If you hav a xts data in monthly, quarterly and yearly frequency it maby be useful (use packages: xts, stats, data.table, zoo)

    xts_ts <- function(xts_data) {
      freq_list <-
        data.table::data.table(
          freq = c('month', 'quarter', 'year'),
          freq_n = c(12L, 4L, 1L),
          freq_format = c('%Y, %m', '%Y, %q', '%Y')
        )
    
      d_ferq <- xts::periodicity(xts_data)[["label"]]
      freq_n <- freq_list[freq == d_ferq, freq_n]
      freq_format <- freq_list[freq == d_ferq, freq_format]
    
      # Put NA if missing date
      empty <-
        zoo::zoo(order.by = seq.Date(zoo::index(xts_data)[1], zoo::index(xts_data)[nrow(xts_data)], by = d_ferq))
      no_misssing <- merge(xts_data, empty)
    
      if (d_ferq == 'quarter') {
        start_date <-
          format(zoo::as.yearqtr(xts::periodicity(xts_data)[["start"]]), freq_format)
    
      } else {
        start_date <-
          format(zoo::as.Date(xts::periodicity(xts_data)[["start"]]), freq_format)
      }
    
      stats::ts(zoo::coredata(no_misssing),
         start = as.integer(strsplit(start_date, split = ',')[[1]]),
         frequency = freq_n)
    }
    

提交回复
热议问题