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.
1 Answer
Reset to default 4Pipes 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
本文标签:
版权声明:本文标题:r - Why does assert_that say that an assertion must return a logical value, when all(between(...)) does return a single logical 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741502147a2382109.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
pipe
tag is about interprocess communication ... – Ben Bolker Commented Feb 14 at 1:47