3

我想用来自 magrittr 的管道重写以下代码:

max(diff(which(diff(runif(50)) > 0 )))

我直接的方法是:

library(magrittr)
runif(50) %>% diff > 0 %>% which %>% diff %>% max

但这失败了,因为 (first) which

runif(50) %>% diff > 0 %>% which

错误其中(。):“哪个”的参数不合逻辑

我不确定为什么会发生此错误以及为什么管道似乎与管道到其他函数不同,因为“diff > 0”的输出是一个逻辑向量。

在旁注中,坦率地说,是否有办法进行比较

 runif(50) %>% diff %>% > 0 
4

2 回答 2

6

尝试:

runif(50) %>% diff %>% `>`(0) %>% which %>% diff %>% max

编辑:可能应该指出那些是反引号,而不是引号。

于 2016-01-29T12:06:34.213 回答
1

我相信您有问题的字符串被解析为等同于:

(runif(50) %>% diff) > (0 %>% which %>% diff %>% max)

它返回相同的错误。

另一方面,除了已经提出的内容之外,这些都可以正常工作:

runif(50) %>% {diff(.) > 0} %>% which %>% diff %>% max
(runif(50) %>% diff > 0) %>% which %>% diff %>% max
于 2017-06-30T12:28:19.597 回答