gpt4 book ai didi

R xts 和 data.table

转载 作者:行者123 更新时间:2023-12-04 00:19:47 27 4
gpt4 key购买 nike

我可以像处理 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com