Skip to content

Commit

Permalink
Make sure constructors never set rownames
Browse files Browse the repository at this point in the history
.xts() tried to remove rownames before setting dimnames (if they came
through via '...'). Setting dimnames can potentially add rownames.
  • Loading branch information
joshuaulrich committed Oct 21, 2022
1 parent 1f5126b commit 920488d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 13 deletions.
15 changes: 8 additions & 7 deletions R/xts.R
Original file line number Diff line number Diff line change
Expand Up @@ -254,13 +254,6 @@ function(x=NULL, index, tclass=c("POSIXct","POSIXt"),
xx <- .Call(C_add_xtsCoreAttributes, x, index_out, tzone., tclass.,
c('xts','zoo'), tformat.)

# ensure there are no rownames
rn <- dimnames(xx)[[1]]
if(!is.null(rn)) {
attr(xx, '.ROWNAMES') <- rn
dimnames(xx)[1] <- list(NULL)
}

# remove any index attributes that came through '...'
# and set any user attributes (and/or dim, dimnames, etc)
dots.names <- eval(substitute(alist(...)))
Expand All @@ -270,6 +263,14 @@ function(x=NULL, index, tclass=c("POSIXct","POSIXt"),
dot.attrs[drop.attr] <- NULL
attributes(xx) <- c(attributes(xx), dot.attrs)
}

# ensure there are no rownames (they may have come though dimnames)
rn <- dimnames(xx)[[1]]
if(!is.null(rn)) {
attr(xx, '.ROWNAMES') <- rn
dimnames(xx)[1] <- list(NULL)
}

xx
}

Expand Down
15 changes: 9 additions & 6 deletions inst/tinytest/test-xts.R
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,15 @@ expect_identical(tf, attr(attr(x, "index"), "tformat"),
expect_identical(tf, attr(attr(y, "index"), "tformat"),
info = ".xts(..., tformat = 'foo') adds tformat to index")

# .xts()
info_msg <- "test..xts_dimnames_in_dots"
x <- .xts(1:5, 1:5, dimnames = list(NULL, "x"))
y <- xts(1:5, index(x), dimnames = list(NULL, "x"))
expect_equal(x, y, info = info_msg)
expect_null(rownames(x), info = "xts() and .xts() apply dimnames passed via '...'")

### dimnames come through '...'
x <- xts(1:5, .Date(1:5), dimnames = list(NULL, "x"))
y <- .xts(1:5, 1:5, dimnames = list(NULL, "x"))
expect_equal(colnames(x), colnames(y), info = "xts() and .xts() apply dimnames passed via '...'")
x <- xts(1:5, .Date(1:5), dimnames = list(1:5, "x"))
y <- .xts(1:5, 1:5, dimnames = list(1:5, "x"))
expect_null(rownames(x), info = "xts() doesn't set rownames when dimnames passed via '...'")
expect_null(rownames(y), info = ".xts() doesn't set rownames when dimnames passed via '...'")

m <- matrix(1, dimnames = list("a", "b"))
x <- .xts(m, 1)
Expand Down

0 comments on commit 920488d

Please sign in to comment.