Skip to content

Commit

Permalink
Merge pull request #17 from weirichs/asNumericIfPossible_checkmate
Browse files Browse the repository at this point in the history
added checks for logical arguments and varName in main function
  • Loading branch information
grewered committed Feb 22, 2024
2 parents ced70da + cda74a6 commit f06e6e9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
4 changes: 4 additions & 0 deletions R/asNumericIfPossible.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
asNumericIfPossible <- function(x, maintain.factor.scores = TRUE, force.string = TRUE, transform.factors = TRUE, varName = NULL) {
checkmate::assert_logical(maintain.factor.scores, len = 1)
checkmate::assert_logical(force.string, len = 1)
checkmate::assert_logical(transform.factors, len = 1)
checkmate::assert_character(varName, null.ok = TRUE)
UseMethod("asNumericIfPossible")
}

Expand Down
15 changes: 14 additions & 1 deletion tests/testthat/test_asNumericIfPossible.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ test_that("Default", {
expect_error(asNumericIfPossible(vec_test),
"Unknown input type or class. Input has to be of class numeric, factor, character or data.frame. If you have used a specific package to import data (e.g., haven) consider transforming your data to factor or character beforehand.", fixed = TRUE)
})

test_that("Numeric vector", {
expect_equal(asNumericIfPossible(num), num)
})
Expand Down Expand Up @@ -52,6 +51,20 @@ test_that("Character vector (levels always kept, maintain scores has not impact)
c(NA_real_, NA_real_, NA_real_))
})

test_that("If input for maintain.factor.scores, force.string and transform.factors are not scalar logical, it throws an error.", {
expect_error(
asNumericIfPossible(char_num, maintain.factor.scores = "TRUE"),
"Assertion on 'maintain.factor.scores' failed: Must be of type 'logical', not 'character'."
)
expect_error(
asNumericIfPossible(char_num, force.string = 3),
"Assertion on 'force.string' failed: Must be of type 'logical', not 'double'."
)
expect_error(
asNumericIfPossible(char_num, transform.factors = c(TRUE, TRUE)),
"Assertion on 'transform.factors' failed: Must have length 1, but has length 2."
)
})

# data frames
#######
Expand Down

0 comments on commit f06e6e9

Please sign in to comment.