Skip to content

Commit

Permalink
correlate() no longer sets the diagonal of 1x1 correlation matrix.
Browse files Browse the repository at this point in the history
As a side effect, correlate() now works with numeric vectors and one-column dfs.

Close tidymodels#120. Close tidymodels#121.
  • Loading branch information
antoine-sachet committed Oct 28, 2020
1 parent 170e571 commit ce1f5c1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
2 changes: 1 addition & 1 deletion R/utility.R
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ as_cordf <- function(x, diagonal = NA) {
stop("Input object x is not a square. ",
"The number of columns must be equal to the number of rows.")
}
diag(x) <- diagonal
if (ncol(x) > 1) diag(x) <- diagonal
new_cordf(x, names(x))
}

Expand Down
13 changes: 13 additions & 0 deletions tests/testthat/test-correlate.R
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,16 @@ test_that("Diagonal sets correctly", {
expect_equal(all(is.na(diag(as.matrix(correlate(d, diagonal = NA)[, -1])))), TRUE)
expect_equal(all(diag(as.matrix(correlate(d, diagonal = 100)[, -1] == 100))), TRUE)
})


test_that("correlate works with numeric vectors", {
expect_equal(correlate(x = 1:10, y = 1:10)[[2]], 1)
expect_equal(correlate(x = 1:10, y = -(1:10), diagonal = 0)[[2]], -1)
})

test_that("correlate works with a one-column data.frame", {
var <- "Sepal.Length"
expect_equal(correlate(datasets::iris[var])[[1]], var)
expect_equal(correlate(datasets::iris[var])[[2]], 1)

})

0 comments on commit ce1f5c1

Please sign in to comment.