tests/testthat/test-cv_index.R

context("Tests for cv_index function")
library(binclass)

test_that( "cv_index runs without error", {
  expect_silent( cv_index( 10, 100 ) )
})

test_that( "cv_index creates balanced groups", {
  index = cv_index( 3, 90 )
  tbl = table( index )
  expect_true( all( tbl == 30 ) )
})

test_that( "cv_index randomized order", {
  index_1 = cv_index( 3, 90 )
  index_2 = cv_index( 3, 90 )
  expect_true( !all( index_1 == index_2 ) )
})

test_that( "cv_index handles unequal groups", {
  index = cv_index( 2, 11 )
  tbl = table( index )
  # First group should be larger than second
  expect_true( all( tbl[1] > tbl[2] ) )
})

test_that( "setting seed leads to reproducible results", {
  index_1 = cv_index( 2, 50, rng_seed = 100 )
  index_2 = cv_index( 2, 50, rng_seed = 100 )
  expect_true( all( index_1 == index_2 ) )
})

test_that( "cv_index balances low counts", {
  x = c( rep(1,5), rep(0,95) )
  index = cv_index( 5, length(x), x = x )
  tbl_1 = table( index[ x == 1 ] )
  tbl_0 = table( index[ x == 0 ] )
  expect_true( all( tbl_1 == 1 ) )
  expect_true( all( tbl_0 == 19 ) )
})

test_that( "cv_index works with factors", {
  x = c( rep('Yes',5), rep('No',95) )
  x = as.factor( x )
  index = cv_index( 5, length(x), x = x )
  tbl_1 = table( index[ x == 'Yes' ] )
  tbl_0 = table( index[ x == 'No' ] )
  expect_true( all( tbl_1 == 1 ) )
  expect_true( all( tbl_0 == 19 ) )
})

test_that( "cv_index provides warning for n_folds > n_obs", {
  expect_warning( cv_index( 20, 10 ) )
})

test_that( "cv_index provides warning when cannot balance", {
  x = c( rep( 1, 4 ), rep( 0, 96 ) )
  expect_warning( cv_index( 5, length(x), x = x ) )
})

test_that( "cv_index witholds desired proportion for testing", {
  index = cv_index( .3, 100 )
  tbl = table( index )
  expect_true( tbl[2] == 30 )
})

test_that( "cv_index handles unequal groups for proportions as well", {
  # Create unbalanced data
  x = c( rep( 1, 10 ), rep( 0, 90 ) )
  index = cv_index( .3, length(x), x = x )
  t1 = table( index[ x == 1 ] )
  t2 = table( index[ x == 0 ] )
  # Should have 3 and 27 for each group, respectively
  expect_true( t1[2] == 3 & t2[2] == 27 )
})
rettopnivek/binclass documentation built on May 13, 2019, 4:46 p.m.