I'm writing a very simple piece of R code that, among other things, uses assert_that
to check that a value is between 0 and 1. It should throw an error if the variable in the data frame is outside this range.
This simple code throws an error that says Error: assert_that: assertion must return a logical value
, but all(between(...))
does return a single logical value of TRUE
.
library(assertthat)
library(tidyverse)
data <- tibble(`Var 1` = c(0.1, 0.2, 0.5), `Var 2` = c(0.1, 2, 5))
data %>%
assert_that(all(between(`Var 1`, 0, 1)))
Why is assert_that
failing here? I'm using backticks in the variable name because the actual code file has spaces in the variable names so I'm emulating that in my minimal example.
Pipes pass their input as the first argument of the functional expression on the right-hand side (or at least the first unmatched argument). Your pipe expression is equivalent to evaluating
assert_that(data, all(between(`Var 1`, 0, 1)))
The first thing assert_that
is testing for TRUE/FALSE is data
, which isn't a logical value ...
I don't know if there's a more rlang
-ish way to do this, but
data |>
with(expr=all(between(`Var 1`, 0, 1))) |>
assert_that()
seems to work.
If it were me I would just skip the pipe:
assert_that(all(between(data[["Var 1"]], 0, 1)))
@zephryl points to this related question, which points out that you should also be able to do this with %$%
, the magrittr exposition pipe:
library(magrittr)
data %$% assert_that(all(between(`Var 1`, 0, 1))) ## TRUE