Skip to content

Commit

Permalink
Ensure Ops.xts results has index and no names
Browse files Browse the repository at this point in the history
Calling Ops.xts() on a matrix and a xts object without a dim attribute
can result in an xts object without an index, and/or with a names
attribute.

Ensure there is never a names attribute, and that we always check if
the index exists.

Tests only exercise the subtraction operator. There should be tests
that use relational operators.

See #295.
  • Loading branch information
joshuaulrich committed May 1, 2019
1 parent 3a6bf2d commit 1b02812
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
2 changes: 1 addition & 1 deletion R/Ops.xts.R
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ function(e1, e2)
#.Call('add_xts_class', e)
.Call('add_class', e, CLASS, PACKAGE="xts")
}
else
if(is.null(attr(e,'index'))) {
if(is.xts(e1)) {
e <- .xts(e, .index(e1))
Expand All @@ -64,5 +63,6 @@ function(e1, e2)
dimnames(e)[[1]] <- list(NULL)
}
}
attr(e, "names") <- NULL
e
}
54 changes: 54 additions & 0 deletions inst/unitTests/runit.Ops.R
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,57 @@ test.xts1d_minus_vector_names <- function() {
colnames(x) <- colnames(y) <- "x"
checkIdentical(x-M, y)
}

### xts vector, matrix/vector
test.xts_vector_minus_matrix1d <- function() {
rn <- format(.POSIXct(1:3))
cn <- "x"
x <- drop(.xts(1:3, 1:3))
m <- matrix(1:3, 3, 1, dimnames = list(rn, cn))
y <- .xts(1:3*0L, 1:3, dimnames = list(NULL, cn))

# use checkEquals because attributes change order
checkEquals(x-m, y)
# test again with no rownames
rownames(m) <- NULL
checkEquals(x-m, y)
# test again with no rownames or colnames
colnames(m) <- colnames(y) <- NULL
checkEquals(x-m, y)
# test again with only colnames
colnames(m) <- colnames(y) <- cn
checkEquals(x-m, y)
}

test.xts_vector_minus_matrix2d <- function() {
# FIXME:
rn <- format(.POSIXct(1:3))
cn <- c("x", "y")
x <- drop(.xts(1:3, 1:3))
m <- matrix(1:6, 3, 2, dimnames = list(rn, cn))
y <- .xts(cbind(1:3*0L, 1:3-4:6), 1:3, dimnames = list(NULL, cn))

# use checkEquals because attributes change order
checkEquals(x-m, y)
# test again with no rownames
rownames(m) <- NULL
checkEquals(x-m, y)
# test again with no rownames or colnames
colnames(m) <- colnames(y) <- NULL
checkEquals(x-m, y)
# test again with only colnames
colnames(m) <- colnames(y) <- cn
checkEquals(x-m, y)
}

test.xts_vector_minus_vector <- function() {
# FIXME:
m <- 1:3
x <- drop(.xts(m, 1:3))
y <- drop(.xts(m*0L, 1:3))

checkIdentical(x-m, y)
# add names to vector
names(m) <- format(index(x))
checkIdentical(x-m, y)
}

0 comments on commit 1b02812

Please sign in to comment.