admin管理员组

文章数量:1291284

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.

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.

Share Improve this question edited Feb 14 at 2:33 zephryl 17.3k4 gold badges16 silver badges34 bronze badges asked Feb 13 at 23:32 Michael AMichael A 4,6158 gold badges40 silver badges64 bronze badges 3
  • 1 Relevant: stackoverflow/q/71277746/17303805 – zephryl Commented Feb 14 at 1:04
  • I wonder if there's a tag for R pipes? The pipe tag is about interprocess communication ... – Ben Bolker Commented Feb 14 at 1:47
  • 1 @BenBolker there’s [magrittr]… otherwise I suppose we could start [r-pipe] for base pipe-related questions. – zephryl Commented Feb 14 at 2:32
Add a comment  | 

1 Answer 1

Reset to default 4

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

本文标签: