r - 将 xts 对象转换为有用的数据框

标签 r dataframe xts

名为 d 的数据框包含以下数据:

timestamp,value
"2013-06-02 00:00:00",70
"2013-06-02 00:02:00",70
"2013-06-02 00:07:00",60
"2013-06-02 00:15:00",70
"2013-06-02 00:12:00",60
"2013-06-02 00:30:00",70
"2013-06-02 00:45:00",70
"2013-06-02 01:00:00",70

我的代码是:
 d = read.csv(path, header=TRUE, sep=",")
 d2 <- xts(x = d[c("value")], order.by = as.POSIXct(d[, "timestamp"], tz = "GMT", format = "%Y-%m-%d %H:%M:%S"))
ends <- endpoints(d2, on = "minutes", k = 15)
d3   <- period.apply(d2, ends, mean)

之后我想将 xts 对象转换为数据帧,我正在使用这个:
d3$timestamp = rownames(d3)
rownames(d3) = NULL
d3$timestamp = strptime(d3$timestamp, "%Y-%m-%d %H:%M:%S")

但是,在最后一步中,它会打印错误:
Error in NextMethod(.Generic) : 
   number of items to replace is not a multiple of replacement length

当我观察到在整个命令后键入 d3 时,对象具有以下数据格式:
                         timestamp
2013-06-02 00:15:00        65
2013-06-02 00:30:00        70
2013-06-02 00:45:00        70
2013-06-02 01:00:00        70

但是,在列名中,它必须具有名称值,并且第二列具有时间戳,如 here .可能有什么问题?

正确的输出必须是这样的:
      value
        65  2013-06-02 00:15:00
        70  2013-06-02 00:30:00
        70  2013-06-02 00:45:00
        70  2013-06-02 01:00:00 

最佳答案

例如,您可以像这样创建 data.frame:

 data.frame(value=coredata(d3),timestamp=index(d3))
# value           timestamp
# 1    65 2013-06-02 00:12:00
# 2    70 2013-06-02 00:15:00
# 3    70 2013-06-02 00:30:00
# 4    70 2013-06-02 00:45:00
# 5    70 2013-06-02 01:00:00

我建议你也使用 read.zoo将您的数据作为动物园对象读取并避免手动强制 xts。例如:
dat <- read.zoo(text='timestamp,value
"2013-06-02 00:00:00",70
"2013-06-02 00:02:00",70
"2013-06-02 00:07:00",60
"2013-06-02 00:15:00",70
"2013-06-02 00:12:00",60
"2013-06-02 00:30:00",70
"2013-06-02 00:45:00",70
"2013-06-02 01:00:00",70',tz ='' , format = "%Y-%m-%d %H:%M:%S",header=TRUE,
         sep=',')
d2 <- as.xts(dat)

关于r - 将 xts 对象转换为有用的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16963190/

相关文章:

r - 如何在ggplot中写化学式

r - 使用fir {seewave}选择音频文件的频率范围

python - 如何使 pandas dataframe str.contains 搜索更快

python - 如何克服 'ValueError: Wrong number of items passed 2, placement implies 1'错误?

r - 如何使用R通过第一行绑定(bind)具有不同行数的多个数据集

R 函数适用于单个列但不适用于 apply

r - 如何转置数据框以便在 r 中切换行和列?

r - 有没有办法将总和添加到 fviz_eig 图中?

python - 合并和填充 Pandas DataFrames

使用R中的xts和zoo包对时间序列进行重采样