Search code examples
rmagrittr

Pipe column names to assertive


I am trying to use the assertive package for run-time testing, and I would like to pass column names using the pipe.

Here's a simple example:

library(tidyverse)
library(assertive)
df <- tibble(Name = c("DONALD", "JAIME", "LINDA"))

This works but doesn't use the pipe:

assertive::assert_all_are_true(df$Name == str_to_upper(df$Name))

This uses the pipe, but doesn't work:

df %>% assertive::assert_all_are_true(Name == str_to_upper(Name))
#> Error in match.arg(severity): object 'Name' not found

How can I pipe column names to assertive?


Solution

  • We can use with

    library(dplyr)
    df %>% 
         with(., assertive::assert_all_are_true(Name == str_to_upper(Name)))
    

    Or extract the column with .$

    df %>%
        {assertive::assert_all_are_true(.$Name == str_to_upper(.$Name))}
    

    Or with |> from R 4.1.0

    df |> 
        {\(x) assertive::assert_all_are_true(x$Name == str_to_upper(x$Name))}()