tests/testthat/test-estimate.lr.R

context("Tests for estimate.lr function")
library(binclass)

# Create example data
n = 900
K = 4
K_sig = 2
param = c( .25, .75 )
sim = bc_simulate( n, K, K_sig, param = param )
# Set up cross-validation
index = c( rep( 1, 600 ), rep( 2, 300 ) )
dat = train_test( 2, index, sim$y, sim$X )

# For debugging purposes
# control = list()

fit = bc_estimate( 'glm', dat )
test_that( "bc_estimate class works", {
  expect_true( is.bc_estimate( fit ) )
})

val = coef( fit )
tst = coef( fit$fit )
names( tst ) = c( 'Intercept', names(tst)[-1] )
test_that( "coefficients are extracted correctly", {
  expect_equal( val, tst[-1] )
  expect_equal( coef( fit, int = T ), tst )
  expect_length( coef( fit, sig = F ), length( coef( sim ) ) + 1 )
})

test_that( "bc_estimate print method works", {
  expect_output( print( fit ) )
})

test_that( "features are extracted correctly", {
  expect_equal( features( fit ), names( val ) )
})

test_that( "bc_estimate levels method works correctly", {
  expect_equal( levels( fit ), levels( dat ) )
})


test_that( "bc_estimate control options work correctly", {

  # Select subset of predictors
  cntrl = list( col_sel = 3:4 )
  fit = bc_estimate( 'glm', dat, control = cntrl )

  # Suppress second round of fitting
  frm = 'y ~ P1 + P2 + P3 + P4'
  dtba = as.data.frame( dat, train = T )
  ex_fit = stats::glm( as.formula( frm ),
                family = 'binomial',
                data = dtba )
  cntrl = list( second_pass = FALSE )
  fit = bc_estimate( 'glm', dat, control = cntrl )
  expect_equal( fit$fit, ex_fit )

  # Pass in previous fit object instead of fitting anew
  cntrl = list( prev_fit = fit$fit )
  new_fit = bc_estimate( 'glm', dat, control = cntrl )

  # Pass in set of coefficients instead of fitting anew
  cntrl = list( prev_coef = coef( fit$fit ) )
  new_fit_2 = bc_estimate( 'glm', dat, control = cntrl )

  # For debugging
  # control = list( prev_coef = coef( fit$fit ) )

})
rettopnivek/binclass documentation built on May 13, 2019, 4:46 p.m.