Converting a data frame to xts

后端 未结 9 887
暗喜
暗喜 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:35

    Well, as.xts assumes by default that the dates are stored in the rownames of the data.frame. Hence the error message. A quick and dirty fix is:

    rownames(q) = q[1]
    as.xts(q)
    

    But you get an extra column with the dates string. Ideally you would construct the data.frame with the dates as rownames to start with.

    0 讨论(0)
  • 2020-11-28 04:38

    Here is a posible solution:

    library(timetk)
    q <- xts::xts(q[,-1], order.by = q$t)
    
    0 讨论(0)
  • 2020-11-28 04:42

    I defined an index with the length equal to the number of rows of my tibble. Only after defining the time sequence separately as shown with the example:

    ti= seq(from = ymd_hm("2000-01-01 00:00"),
    to = ymd_hm("2000-01-02 01:00"), by =  "30 min", tz = "UTC")
    
    tbl <- tibble(t =ti,
        x = 1:length(t))
    )
    

    This code worked:

    xts.tbl <- xts(tbl[,-1], order.by = ti)
    

    However all data transformed into characters.

    0 讨论(0)
  • 2020-11-28 04:48

    This is clearly documented --- xts and zoo objects are formed by supplying two arguments, a vector or matrix carrying data and Date, POSIXct, chron, ... type supplying the time information (or in the case of zoo the ordering).

    So do something like

     qxts <- xts(q[,-1], order.by=q[,1])
    

    and you should be set.

    0 讨论(0)
  • 2020-11-28 04:48

    You can simply do the following

    qxts <- xts(q[,2],q$t)
    

    Worked for me.

    0 讨论(0)
  • 2020-11-28 04:53

    The reason, why it did not work now seems clear, xts does not accept tibbles and even if columns are selected they are still stored as Tibbles. Either the core data may be transformed to matrix ore a vector.The following code works: xls.tbl <- xls(tbl$x, order.by = tbl$t)

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