Converting a data frame to xts

后端 未结 9 888
暗喜
暗喜 2020-11-28 04:10

I\'m trying to convert a data frame to xts object using the as.xts()-method. Here is my input dataframe q:

q
                      t x  
1  2006-01-01 00:00:         


        
相关标签:
9条回答
  • 2020-11-28 04:53

    Try the following

    q$t<-as.xts(q, order.by = as.Date(q$t), dateFormat="POSIXct")
    
    0 讨论(0)
  • 2020-11-28 04:57

    A simple solution is to first convert the data.frame to a data.table:

    library(data.table)
    
    qxts <- as.xts(as.data.table(q))
    
    0 讨论(0)
  • 2020-11-28 05:02

    Here's a solution using the tidyquant package, which contains a function as_xts() that coerces a data frame to an xts object. It also contains as_tibble() to coerce xts objects to tibbles ("tidy" data frames).

    Recreate the data frame (note that the date-time class is used in "tidy" data frames, but any unambiguous date or date time class can be used):

    > q
    # A tibble: 3 × 2
                        t     x
                   <dttm> <dbl>
    1 2006-01-01 00:00:00     1
    2 2006-01-01 01:00:00     2
    3 2006-01-01 02:00:00     3
    

    Use as_xts() to convert to "xts" class. Specify the argument, date_col = t, to designate the "t" column as the dates to use as row names:

    > library(tidyquant)
    > as_xts(q, date_col = t)
                        x
    2006-01-01 00:00:00 1
    2006-01-01 01:00:00 2
    2006-01-01 02:00:00 3
    

    The return is an xts object with the proper date or date-times as row names.

    0 讨论(0)
提交回复
热议问题