Test whether variables in a data frame are labelled in a given way.
expect_labels(
vars,
val_labels = NULL,
var_label = NULL,
flt = TRUE,
data = get_testdata()
)
<tidy-select
> A set of columns to
test.
What value label check should be performed? One of:
A character vector of expected value labels.
A named vector of expected label-value pairs.
TRUE
to test for the presence of value labels in general.
FALSE
to test for the absence of value labels.
NULL
to ignore value labels when checking.
What variable label check should be performed? One of:
A character vector of expected variable labels.
TRUE
to test for the presence of a variable labels.
FALSE
to test for the absence of a variable labels.
NULL
to ignore the variable label when checking.
<data-masking
> A filter specifying
a subset of the data frame to test.
A data frame to test. The global test data is used by default.
expect_*()
functions are mainly called for their side effects. The
expectation signals its result (e.g. "success", "failure"), which is logged
by the current test reporter. In a non-testing
context the expectation will raise an error with class
expectation_failure
if it fails.
df <- data.frame(
x = labelled::labelled(c("M", "M", "F"), c(Male = "M", Female = "F"), "Sex"),
y = labelled::labelled(c("M", "M", "F"), c(Male = "M", Female = "F", Other = "X")),
z = c("M", "M", "F")
)
# Check for a value-label pairing
try(expect_labels(x, c(Male = "M"), data = df))
#> Error : `df` has 1 records failing label check on variable `x`.
#> Variable set: `x`
#> Filter: None
#> Arguments: `val_labels = <chr: Male = "M">, var_label = NULL`
# Check that two variables have the same values
expect_labels(x, labelled::val_labels(df$y), data = df) # N.B. This passes!
# Check for the presence of a particular label
try(expect_labels(x, "Male", data = df))
#> Error : `df` has 1 records failing label check on variable `x`.
#> Variable set: `x`
#> Filter: None
#> Arguments: `val_labels = "Male", var_label = NULL`
expect_labels(x, var_label = "Sex", data = df)
# Check that a variable is labelled at all
try(expect_labels(z, val_labels = TRUE, data = df))
#> Error : `df` has 3 records failing label check on variable `z`.
#> Variable set: `z`
#> Filter: None
#> Arguments: `val_labels = TRUE, var_label = NULL`
try(expect_labels(z, var_label = TRUE, data = df))
#> Error : `df` has 3 records failing label check on variable `z`.
#> Variable set: `z`
#> Filter: None
#> Arguments: `val_labels = NULL, var_label = TRUE`
# Check that a variable isn't labelled
expect_labels(z, val_labels = FALSE, data = df)
expect_labels(z, var_label = FALSE, data = df)