名为 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/