Skip to content

Commit

Permalink
fix: check type of column roles (#1131)
Browse files Browse the repository at this point in the history
* fix: check type of column roles

* repair checks for tasks with arbitrary row ids

---------

Co-authored-by: Michel Lang <michellang@gmail.com>
  • Loading branch information
be-marc and mllg authored Aug 29, 2024
1 parent e90632a commit 57b6109
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
14 changes: 14 additions & 0 deletions R/Task.R
Original file line number Diff line number Diff line change
Expand Up @@ -1195,6 +1195,20 @@ task_check_col_roles = function(self, new_roles) {
}
}

# check weights
if (length(new_roles[["weight"]])) {
weights = self$backend$data(self$backend$rownames, cols = new_roles[["weight"]])
assert_numeric(weights[[1L]], lower = 0, any.missing = FALSE, .var.name = names(weights))
}

# check name
if (length(new_roles[["name"]])) {
row_names = self$backend$data(self$backend$rownames, cols = new_roles[["name"]])
if (!is.character(row_names[[1L]]) && !is.factor(row_names[[1L]])) {
stopf("Assertion on '%s' failed: Must be of type 'character' or 'factor', not %s", names(row_names), class(row_names[[1]]))
}
}

if (inherits(self, "TaskSupervised")) {
if (length(new_roles$target) == 0L) {
stopf("Supervised tasks need at least one target column")
Expand Down
19 changes: 19 additions & 0 deletions tests/testthat/test_Task.R
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,25 @@ test_that("groups/weights work", {
}, "up to one")
})

test_that("col roles are valid", {
b = as_data_backend(data.table(
y = runif(20),
logical = sample(c(TRUE, FALSE), 20, replace = TRUE),
numeric = runif(20),
integer = sample(1:3, 20, replace = TRUE),
factor = factor(sample(letters[1:3], 20, replace = TRUE))))
task = TaskRegr$new("test", b, target = "y")

# weight
expect_error(task$set_col_roles("logical", roles = "weight"), "type")
expect_error(task$set_col_roles("factor", roles = "weight"), "type")

# name
expect_error(task$set_col_roles("logical", roles = "name"), "type")
expect_error(task$set_col_roles("integer", roles = "name"), "type")
expect_error(task$set_col_roles("numeric", roles = "name"), "type")
})

test_that("ordered factors (#95)", {
df = data.frame(
x = c(1, 2, 3),
Expand Down

0 comments on commit 57b6109

Please sign in to comment.