R xts 和 data.table

标签 r xts data.table

我可以像处理 data.frame 一样将 data.table 转换为 xts 对象:

> df = data.frame(x = c("a", "b", "c", "d"), v = rnorm(4))
> dt = data.table(x = c("a", "b", "c", "d"), v = rnorm(4))
> xts(df, as.POSIXlt(c("2011-01-01 15:30:00", "2011-01-02 15:30:00", "2011-01-03 15:50:50", "2011-01-04 15:30:00")))
                    x   v           
2011-01-01 15:30:00 "a" "-1.2232283"
2011-01-02 15:30:00 "b" "-0.1654551"
2011-01-03 15:50:50 "c" "-0.4456202"
2011-01-04 15:30:00 "d" "-0.9416562"
> xts(dt, as.POSIXlt(c("2011-01-01 15:30:00", "2011-01-02 15:30:00", "2011-01-03 15:50:50", "2011-01-04 15:30:00")))
                    x   v           
2011-01-01 15:30:00 "a" " 1.3089579"
2011-01-02 15:30:00 "b" "-1.7681071"
2011-01-03 15:50:50 "c" "-1.4375100"
2011-01-04 15:30:00 "d" "-0.2467274"

在 xts 中使用 data.table 有什么问题吗?

最佳答案

只是为了解决一个悬而未决的问题。

正如文森特在评论中指出的那样,这没有问题。

它包含在数据表 1.9.5 中。下面是类似的内容:

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)
}

关于R xts 和 data.table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9295209/

相关文章:

r - 关于如何在 xts 中获取下一个/上一个元素的基本问题

r - 将列表列中的值分派(dispatch)到单独的列

r - 运行长度的累积和。这个循环可以矢量化吗?

r - 初学者 R 类(class)的结构

R- Shiny | cat(list(...),file,sep,fill,labels,append)中的错误: argument 1 (type 'list' ) cannot be handled by 'cat'

r - 在 quantmod 中更新历史价格

r - 在 R 上安装 xts 包时出错

r - 多次有效地子集 data.table

r - 表格格式不会显示 x 值

c++ - 有没有办法让 Rcpp 停止定义 NDEBUG?