Skip to content

Commit

Permalink
Merge pull request #56 from mayer79/test-convert-revert
Browse files Browse the repository at this point in the history
Add unit test, some formatting
  • Loading branch information
mayer79 committed Oct 28, 2023
2 parents 10bd353 + d77d8ea commit bde303e
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 8 deletions.
10 changes: 8 additions & 2 deletions R/missRanger.R
Original file line number Diff line number Diff line change
Expand Up @@ -375,8 +375,14 @@ convert <- function(X, check = FALSE) {
stopifnot(is.data.frame(X))

if (!ncol(X)) {
return(list(X = X, bad = character(0), vars = character(0),
types = character(0), classes = character(0)))
out <- list(
X = X,
bad = character(0),
vars = character(0),
types = character(0),
classes = character(0)
)
return(out)
}

types <- vapply(X, typeof2, FUN.VALUE = "")
Expand Down
14 changes: 8 additions & 6 deletions R/pmm.R
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@
#' pmm(xtrain = c("A", "A", "B"), xtest = "A", ytrain = c(2, 2, 4), k = 2) # 2
#' pmm(xtrain = factor(c("A", "B")), xtest = factor("C"), ytrain = 1:2) # 2
pmm <- function(xtrain, xtest, ytrain, k = 1L, seed = NULL) {
stopifnot(length(xtrain) == length(ytrain),
sum(ok <- !is.na(xtrain) & !is.na(ytrain)) >= 1L,
(nt <- length(xtest)) >= 1L, !anyNA(xtest),
mode(xtrain) %in% c("logical", "numeric", "character"),
mode(xtrain) == mode(xtest),
k >= 1L)
stopifnot(
length(xtrain) == length(ytrain),
sum(ok <- !is.na(xtrain) & !is.na(ytrain)) >= 1L,
(nt <- length(xtest)) >= 1L, !anyNA(xtest),
mode(xtrain) %in% c("logical", "numeric", "character"),
mode(xtrain) == mode(xtest),
k >= 1L
)

xtrain <- xtrain[ok]
ytrain <- ytrain[ok]
Expand Down
23 changes: 23 additions & 0 deletions tests/testthat/test-missRanger.R
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,26 @@ test_that("Extremely wide datasets are handled", {
data[5L, 5L] <- NA
expect_no_error(missRanger(as.data.frame(data), num.trees = 3L, verbose = 0L))
})

test_that("Convert and revert do what they should", {
n <- 20L
X <- data.frame(
x1 = seq_len(n),
x2 = rep(LETTERS[1:4], n %/% 4),
x3 = factor(rep(LETTERS[1:2], n %/% 2)),
x4 = seq_len(n) > n %/% 3,
x5 = seq(as.Date("2008-11-01"), as.Date("2008-11-21"), length.out = n)
)
X <- generateNA(X, seed = 1L)
conv <- convert(X)
reve <- revert(conv)

expect_equal(X, reve)
expect_equal(
unname(sapply(conv$X, class)),
c("integer", "factor", "factor", "factor", "numeric")
)

Ximp <- missRanger(X, seed = 1L, verbose = FALSE, pmm.k = 3L)
expect_equal(sapply(Ximp, class), sapply(X, class))
})

0 comments on commit bde303e

Please sign in to comment.