Convert data frame with date column to timeseries

后端 未结 5 900
走了就别回头了
走了就别回头了 2020-11-29 20:06

I\'ve got a data frame with the following data:

>PRICE
         DATE  CLOSE
1    20070103 54.700
2    20070104 54.770
3    20070105 55.120
4    20070108 5         


        
5条回答
  •  余生分开走
    2020-11-29 20:53

    Whether you want to convert a data frame (or any time series) to a xts or zoo object, as in the answers above, or to any other time series (such as a ts object) the tsbox package makes coercion easy:

    PRICE <- structure(list(
      DATE = c(20070103L, 20070104L, 20070105L, 20070108L, 20070109L,
               20070110L, 20070111L, 20070112L, 20070115L),
      CLOSE = c(54.7, 54.77, 55.12, 54.87, 54.86, 54.27, 54.77, 55.36, 55.76)),
      .Names = c("DATE", "CLOSE"), class = "data.frame",
      row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9"))
    
    library(tsbox)
    
    ts_xts(PRICE)
    #> [time]: 'DATE' [value]: 'CLOSE'
    #> Loading required namespace: xts
    #> Registered S3 method overwritten by 'xts':
    #>   method     from
    #>   as.zoo.xts zoo
    #>            CLOSE
    #> 2007-01-03 54.70
    #> 2007-01-04 54.77
    #> 2007-01-05 55.12
    #> 2007-01-08 54.87
    #> 2007-01-09 54.86
    #> 2007-01-10 54.27
    #> 2007-01-11 54.77
    #> 2007-01-12 55.36
    #> 2007-01-15 55.76
    
    ts_ts(PRICE)
    #> [time]: 'DATE' [value]: 'CLOSE'
    #> Time Series:
    #> Start = 2007.00547581401 
    #> End = 2007.0383306981 
    #> Frequency = 365.2425 
    #>  [1] 54.70 54.77 55.12    NA    NA 54.87 54.86 54.27 54.77 55.36    NA
    #> [12]    NA 55.76
    

提交回复
热议问题