简体   繁体   English

如何将管道变成不平等?

[英]How to feed pipe into an inequality?

This has come up in multiple instances, and I do not know if this current instance is generalizable to the many cases where this arises for me, but I'm hoping an answer may shed some light. 这已经出现在多个实例中,我不知道这个当前实例是否适用于我出现的许多情况,但我希望答案可能会有所启发。

The simplest version of this is when I am doing some data processing and want to perform an evaluation on the result of a pipe. 最简单的版本是当我进行一些数据处理并想要对管道的结果进行评估时。 A simple example would be: 一个简单的例子是:

> seq(9) %>% > 4
Error: unexpected '>' in "seq(9) %>% >"
> seq(9) %>% . > 4
Error in .(.) : could not find function "."

The desired output would be a logical vector 期望的输出将是逻辑矢量

FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE

In many circumstances I want to evaluate on some piped output but have to assign it and then perform the evaluation for it to work: 在许多情况下,我想评估一些管道输出,但必须分配它,然后执行评估才能工作:

seq(9) -> vec
vec > 4

Is there a way to complete these sorts of evaluations within a pipe chain entirely? 有没有办法完全在管道链中完成这些类型的评估?

You need to use curly braces if you just want to use pipes. 如果您只想使用管道,则需要使用花括号。

seq(9) %>% {. > 4}

[1] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE

I'd recommend using purrr if you're going to be piping these kinds of things, as it will result in a bit more readable code. 我推荐使用purrr如果你要管道这些东西,因为它会导致更易读的代码。

library(purrr)

map_lgl(seq(9), ~.x > 4)

[1] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE

One more option is to call the > function as a function rather than an operator: 还有一个选择是将>函数称为函数而不是运算符:

> seq(9) %>% `>`(4)
[1] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
> seq(9) %>% '>'(4)
[1] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE

I think the backquotes make the most sense, but regular quotes do work in this case as well. 我认为反引号最有意义,但是在这种情况下,常规引号也可以。

magrittr provides "aliases" to turn binary operators into pipe-able functions. magrittr提供“别名”来将二元运算符转换为可管道的函数。 I don't care for them myself, but you can do 我自己并不关心他们,但你可以这样做

library(magrittr)
seq(9) %>% is_greater_than(4)

See the full list at ?add (which is an alias for + ). 请参阅完整列表?add (这是+的别名)。 There are implementations for everything from + to [[ . +[[

In a slightly broader context, this is easily done with mutate : 在稍微宽泛的背景下,使用mutate可以轻松完成:

library(dplyr)
data_frame(x=1:9) %>% mutate(big_x = x>4)

Unsolicited opinion : If you're mostly working with atomic vectors, I suspect that the tidyverse/piping approach is going to be more trouble than it's worth. 未经请求的观点 :如果您主要使用原子载体,我怀疑整流/管道方法会比它的价值更麻烦。 As the other answer suggests, you can use purrr , but again, base R may work perfectly well. 正如另一个答案所暗示的,你可以使用purrr ,但同样,基础R可以很好地工作。 More context for your problem might help. 更多问题的背景可能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM