R xts and data.table

后端 未结 2 1642
执笔经年
执笔经年 2020-12-28 09:24

I can convert a data.table to an xts object just as I do with a data.frame:

> df = data.frame(x = c(\"a\", \"b\", \"c\", \"d\"), v = rnorm(4))
> dt = d         


        
2条回答
  •  被撕碎了的回忆
    2020-12-28 09:49

    Just to resolve an open question.

    As Vincent point in the comment there is no issue about that.

    It is included in data.table 1.9.5. Below is the similar content:

    as.data.table.xts <- function(x, keep.rownames = TRUE){
      stopifnot(requireNamespace("xts") || !missing(x) || xts::is.xts(x))
      r = setDT(as.data.frame(x), keep.rownames = keep.rownames)
      if(!keep.rownames) return(r[])
      setnames(r,"rn","index")
      setkeyv(r,"index")[]
    }
    
    as.xts.data.table <- function(x){
      stopifnot(requireNamespace("xts") || !missing(x) || is.data.table(x) || any(class(x[[1]] %in% c("POSIXct","Date"))))
      colsNumeric = sapply(x, is.numeric)[-1] # exclude first col, xts index
      if(any(!colsNumeric)){
        warning(paste("Following columns are not numeric and will be omitted:",paste(names(colsNumeric)[!colsNumeric],collapse=", ")))
      }
      r = setDF(x[,.SD,.SDcols=names(colsNumeric)[colsNumeric]])
      rownames(r) <- x[[1]]
      xts::as.xts(r)
    }
    

提交回复
热议问题