开发者

Compute range over list of `xts` objects

In R, I've got a list of xts objects and I want to compute the range of the time index over all the items in the list. I can't find a smooth way to do it though, it keeps losing the classes of the objects & becoming raw numeric vectors.

For example (my list is called states, it's indexed by a GMT POSIXct):

> c(min(sapply(states, start)), max(sapply(states, end)))
[1] 1252714110 1315785360

> range(sapply(states, function(x) range(index(x))))
[1] 12527开发者_如何学Python14110 1315785360

It's a hassle to convert those back to POSIXct, I'm doing it like so:

minmax <- range(sapply(states, function(x) range(index(x))))
epoch <-   as.POSIXct(0, origin="1970-01-01", tz="GMT")
rg <- as.POSIXct(minmax, origin="1970-01-01", tz="GMT")

Advice appreciated!


Use lapply to find the index range of each list element. Then use do.call to find the range of the list:

do.call(range, lapply(states, function(x) range(index(x))))

or, if you prefer a functional paradigm:

Reduce(range, Map(function(x) range(index(x)), states))

sapply doesn't work because the simplification process converts the output to an atomic vector or matrix with a single type of either: NULL < raw < logical < integer < real < complex < character < list < expression, in that order of precedence.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜