1library(testthat)
2library(recipes)
3
4dummies <- cbind(model.matrix( ~ block - 1, npk),
5                 model.matrix( ~ N - 1, npk),
6                 model.matrix( ~ P - 1, npk),
7                 model.matrix( ~ K - 1, npk),
8                 yield = npk$yield)
9
10dummies <- as.data.frame(dummies)
11
12dum_rec <- recipe(yield ~ . , data = dummies)
13
14###################################################################
15
16library(modeldata)
17data(biomass)
18biomass$new_1 <- with(biomass,
19                      .1*carbon - .2*hydrogen + .6*sulfur)
20biomass$new_2 <- with(biomass,
21                      .5*carbon - .2*oxygen + .6*nitrogen)
22
23biomass_tr <- biomass[biomass$dataset == "Training",]
24biomass_te <- biomass[biomass$dataset == "Testing",]
25
26biomass_rec <- recipe(HHV ~ carbon + hydrogen + oxygen + nitrogen +
27                        sulfur + new_1 + new_2,
28                      data = biomass_tr)
29
30###################################################################
31
32test_that('example 1', {
33  dum_filtered <- dum_rec %>%
34    step_lincomb(all_predictors())
35  dum_filtered <- prep(dum_filtered, training = dummies, verbose = FALSE)
36  removed <- c("N1", "P1", "K1")
37  expect_equal(dum_filtered$steps[[1]]$removals, removed)
38})
39
40test_that('example 2', {
41  lincomb_filter <- biomass_rec %>%
42    step_lincomb(all_predictors())
43
44  filtering_trained <- prep(lincomb_filter, training = biomass_tr)
45  test_res <- bake(filtering_trained, new_data = biomass_te, all_predictors())
46
47  expect_true(all(!(paste0("new_", 1:2) %in% colnames(test_res))))
48})
49
50test_that('no exclusions', {
51  biomass_rec_2 <- recipe(HHV ~ carbon + hydrogen, data = biomass_tr)
52  lincomb_filter_2 <- biomass_rec_2 %>%
53    step_lincomb(all_predictors())
54
55  filtering_trained_2 <- prep(lincomb_filter_2, training = biomass_tr)
56  test_res_2 <- bake(filtering_trained_2, new_data = biomass_te, all_predictors())
57
58  expect_true(length(filtering_trained_2$steps[[1]]$removals) == 0)
59  expect_true(all(colnames(test_res_2) == c("carbon", "hydrogen")))
60})
61
62
63test_that('printing', {
64  dum_filtered <- dum_rec %>%
65    step_lincomb(all_predictors())
66  expect_output(print(dum_filtered))
67  expect_output(prep(dum_filtered, training = dummies, verbose = TRUE))
68})
69