磁悬浮管(%>%)具有不良行为的原因?

标签 r magrittr

在条件和ifelse分支中都使用转发结果的情况下,我在管道中使用ifelse。以下是简化版本:如果放在大括号内,ifelse +管道似乎只能处理与.不同的条件。


library("magrittr")

FALSE %>%  ifelse(., 'true', 'false')
#> [1] "false"

FALSE %>%  ifelse(. == TRUE, 'true', 'false')
#> Error in ifelse(., . == TRUE, "true", "false"): unused argument ("false")

FALSE %>%  {ifelse(. == TRUE, 'true', 'false')}
#> [1] "false"

我最初的目标:

library("magrittr")

NULL %>% ifelse(is.null(.), "", as.character(.))
#> Error in ifelse(., is.null(.), "", as.character(.)): unused argument (as.character(.))

NULL %>% {ifelse(is.null(.), "", as.character(.))}
#> [1] ""

使用{}对我来说已经足够好,但是我想了解这种现象的原因。

编辑:
尽管this问题讨论了一个相关主题,而我最初看到的是将ifelse放在花括号中的想法,但在表达式/函数调用中仅使用.还是使用.之间没有区别,这是我的问题的重点。

最佳答案

magrittr文档说,在嵌套函数调用中使用点时,其行为如您所见。

Using the dot for secondary purposes
Often, some attribute or property of lhs is desired in the rhs call in addition to the value of lhs itself, e.g. the number of rows or columns. It is perfectly valid to use the dot placeholder several times in the rhs call, but by design the behavior is slightly different when using it inside nested function calls. In particular, if the placeholder is only used in a nested function call, lhs will also be placed as the first argument! The reason for this is that in most use-cases this produces the most readable code.

For example, iris %>% subset(1:nrow(.) %% 2 == 0) is equivalent to iris %>% subset(., 1:nrow(.) %% 2 == 0) but slightly more compact. It is possible to overrule this behavior by enclosing the rhs in braces. For example, 1:10 %>% {c(min(.), max(.))} is equivalent to c(min(1:10), max(1:10)).



因此,建议的解决方案实际上是使用已经发现的花括号。

逻辑求值似乎是ifelse中的一个单独的函数调用,因此它具有这种行为。

关于磁悬浮管(%>%)具有不良行为的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47109900/

相关文章:

r - 用于准确预测的数据集中的最小行数

r - 如何确定以system(...,wait = FALSE)开始的进程何时结束

R:使用管道 %>% 和 pkg::fo 会导致错误 "Error in .::base : unused argument"

r - R 函数中的 Magrittr 管道

r - 如何将行名称添加到 magrittr 链中的数据框

r - 错误: could not find function “%>%”

r - 错误: could not find function "%>%"

r - 使用 magrittr tee %T>% 运算符会产生错误

r - 计算 R 中具有纬度、经度和高程的两点之间的距离

r - R 中的分面或分组相关和相关图