joshuaulrich / xts

Extensible time series class that provides uniform handling of many R time series classes by extending zoo.
http://joshuaulrich.github.io/xts/
GNU General Public License v2.0
219 stars 71 forks source link

first() on a numeric vector with negative argument returns unexpected result #325

Closed vxg20 closed 4 years ago

vxg20 commented 4 years ago

Description

Hi there, there seems to be changes in the way the function first treats vector when given a negative argument.

Expected behavior

previously the function first(vect, -1) will return the original vect minus the number at the first index for xts version 0.11 but now in xts 0.12 the behaviour changes. I am not sure what it is trying to do anymore

Minimal, reproducible example

x <- c(1,2,3,4)

first(x,-1)

this will now return c(3, 4) in xts version 0.12 seems like a bug as the result is quite unexpected ?

braverock commented 4 years ago

The issue, such as there is one, appears to only be on vectors, and not on actual xts objects:

x<-c(1:4)

y<-xts(x,order.by=as.Date(x))

first(x)
# [1] 1

first(x,-1)
# [1] 3 4 # not as expected

y
#            [,1]
# 1970-01-02    1
# 1970-01-03    2
# 1970-01-04    3
# 1970-01-05    4

first(y,-1)
#            [,1]
# 1970-01-03    2
# 1970-01-04    3
# 1970-01-05    4 

first(y,'-1 day')
#            [,1]
# 1970-01-03    2
# 1970-01-04    3
# 1970-01-05    4
joshuaulrich commented 4 years ago

This does look like a bug, but it's not a change in behavior in 0.12-0. This behavior was covered by a unit test before the 0.11-0 release. It was added in commit eb7cc4a8986fca511687b736614c870e39756a2f. If this is a bug, it likely affects last() also.

joshuaulrich commented 4 years ago

I just checked, and found that the existing tests use an input vector of 3 elements. They fail if they are lengthened to 4 elements. So this is certainly a bug.