I'm trying to pipe a vector into an all()
statement to check if all elements are equal to a certain value. I figure I need to use the exposition pipe %$%
since all()
does not have a built-in data argument. My attempt leads to an error:
library(tidyverse)
library(magrittr)
vec <- c("a", "b", "a")
vec %>%
keep(!grepl("b", .)) %$%
all(. == "a")
#> Error in eval(substitute(expr), data, enclos = parent.frame()): invalid 'envir' argument of type 'character'
If I break the pipe before all()
and assign the output to an object p
, and then pass p
to all()
as a second command it works fine:
vec %>%
keep(!grepl("b", .)) -> p
all(p == "a")
#> [1] TRUE
I don't understand why this works while my first attempt does not. I'd like to be able to do this in a single pipe that results in TRUE
.
If vec
is instead a tibble
the following works:
vec <- tibble(var = c("a", "b", "a"))
vec %>%
filter(!grepl("b", var)) %$%
all(.$var == "a")
#> [1] TRUE
This doesn't suit my purposes as well, and I'd for my own understanding to know why my first attempt does not work.