将向量传递给all()以测试相等性 [英] piping a vector into all() to test equality

查看:112
本文介绍了将向量传递给all()以测试相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将向量传递到 all()语句中,以检查所有元素是否都等于某个值。我想我需要使用博览会管道%$%,因为 all()没有内置数据论据。我的尝试导致错误:

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'

如果我在 all()之前断开管道并将输出分配给对象 p ,然后将 p 传递给 all()作为第二个命令,它可以正常工作:

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

我不明白为什么这样做有效,而我的第一次尝试却没有。我希望能够在单个管道中执行此操作,从而导致 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.

如果 vec 而是 tibble 以下作品:

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.

推荐答案

管道的工作方式是它占据了管道的左侧。管道运算符,并将其作为第一个参数传递给右侧函数。因此,在这种情况下,由于需要将data参数修改为 all ,因此需要停止管道将LHS传递给RHS。我们可以使用 {} 来实现。

The way pipe works is it takes the left-hand side of the pipe operator and passes it as a first argument to the right hand side function. So here, in this case as we need to modify the data argument to all , we need to stop pipe from passing the LHS to the RHS. We can do that by using {}.

library(magrittr)

vec %>% purrr::keep(!grepl("b", .)) %>% {all(. == 'a')}
#[1] TRUE






vec 中,让我们检查所有元素是否都是 a b 。我们可以在这里使用%in%


In vec , let's check if all the elements are either "a" or "b". We can use %in% here.

vec <- c("a", "b", "a")

不带管道的普通版本为:

Plain version without pipes would be :

all(vec %in% c('a', 'b'))
#[1] TRUE

如果使用管道,则尝试

vec %>% all(. %in% c('a', 'b'))

我们得到

#[1] NA




警告消息:
总共(。,。%in%c( a, b)):
类型为'character'的强制参数为逻辑

Warning message: In all(., . %in% c("a", "b")) : coercing argument of type 'character' to logical

这里发生了什么

all(vec, vec %in% c('a', 'b'))
#[1] NA




警告消息:
总计(vec,vec%in%c( a, b)):
强制类型为'character'的参数'到逻辑

Warning message: In all(vec, vec %in% c("a", "b")) : coercing argument of type 'character' to logical

会返回相同的消息。

为避免这种情况,我们使用 {}

To avoid this we use {}

vec %>% {all(. %in% c('a', 'b'))}
#[1] TRUE

这给了我们预期的答案。

which gives us the expected answer.

这篇关于将向量传递给all()以测试相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆