我知道这一定是一件容易的事,但我被困住了,无法前进。
我有以下xts:
timestamp id type price size api
2014-05-02 00:02:07 "1398981727" "36833484" "BID" "449.247" "9.00000e-02" "TRUE"
2014-05-02 00:02:07 "1398981727" "36833485" "BID" "449.248" "5.42886e-02" "TRUE"
2014-05-02 00:03:04 "1398981784" "36833488" "BID" "449.246" "4.66000e+00" "TRUE"
2014-05-02 00:03:12 "1398981792" "36833489" "BID" "449.246" "5.90000e-01" "TRUE"
2014-05-02 00:03:12 "1398981792" "36833490" "BID" "449.246" "4.00000e-02" "TRUE"
2014-05-02 00:03:14 "1398981794" "36833491" "BID" "449.246" "2.00000e-02" "TRUE"
2014-05-02 00:03:23 "1398981803" "36833498" "BID" "449.240" "1.00000e-02" "TRUE"
2014-05-02 00:04:55 "1398981895" "36833504" "BID" "448.790" "9.89321e-02" "TRUE"
2014-05-02 00:04:55 "1398981895" "36833505" "BID" "449.108" "1.75000e+00" "TRUE"
2014-05-02 00:04:55 "1398981895" "36833506" "BID" "449.110" "5.21441e-01" "TRUE"
2014-05-02 00:05:26 "1398981926" "36833508" "ASK" "447.000" "5.16985e-01" "TRUE"
2014-05-02 00:05:26 "1398981926" "36833509" "ASK" "446.473" "1.20000e-02" "TRUE"
2014-05-02 00:05:26 "1398981926" "36833510" "ASK" "446.205" "1.04000e-02" "TRUE"
我希望从中为每个给定类型的订单(BID或ASK,列类型)构建包含最后一次观察的另一个xts。
例如对于ASK订单,我想构建像这样的xts:
2014-05-02 00:02:07 NA
2014-05-02 00:03:04 NA
2014-05-02 00:03:12 NA
2014-05-02 00:03:14 NA
2014-05-02 00:03:23 NA
2014-05-02 00:04:55 NA
2014-05-02 00:05:26 446.205
新xts必须包含与旧索引相同的索引。没有ASK订单的时间戳应为NA。
我试过这个
xts(period.apply(temp, INDEX = endpoints(temp, on = "secs", k = 1), FUN = function(x) tail(as.numeric(x$price[x$type == "ASK"]), 1)))
其中temp =上面输入的xts。但它始终伴随着以下错误:
Error in coredata.xts(x) : currently unsupported data type.
有什么想法吗?
答案 0 :(得分:2)
问题是period.apply
用于聚合对象,但您要删除行。这意味着前6个函数评估的结果是numeric(0)
,它们不是观察的有效值。
如果没有观察结果,则需要返回NA
。这意味着如果没有问题观察,你需要稍微修改你的函数以返回NA
。
f <- function(x) {
y <- tail(as.numeric(x$price[x$type == "ASK"]), 1)
if(!length(y)) NA else y
}
period.apply(temp, endpoints(temp, "secs"), f)
这可能是实现目标的更好方法,但您需要提供有关您最终要做的事情的更多详细信息。