使用来自 magrittr 的复合管道 %<>% 似乎没有正确分配

Using the compound pipe %<>% from magrittr doesn't appear to be assigning correctly

我在使用 %<>% 管道时似乎遇到了一些问题。

根据 magrittr 文档

The compound assignment pipe-operator, %<>%, is used to update a value by first piping it into one or more rhs expressions, and then assigning the result. For example, some_object %<>% foo %>% bar is equivalent to some_object <- some_object %>% foo %>% bar. It must be the first pipe-operator in a chain, but otherwise it works like %>%.

但是,我看到了与此相矛盾的行为。这是我的反例(抱歉,它直接来自我的代码)

Temp$IncurralAge <- Temp$IncurralAge %>% round((.-2)/5)*5

完美运行。

Temp$IncurralAge %<>% round((.-2)/5)*5

而是打印与我打印相同的输出

Temp$IncurralAge %>% round((.-2)/5)*5

我看不出这里出了什么问题,有人发现我的语法有问题吗?

None 问题中显示的表达方式与问题似乎相信的方式一致。

R 表达式优先级

%...% 的优先级高于 *,因此 * 在执行 %>% 之后执行,因此 5 的乘法不是右侧的一部分%>% 而是 x %>% round(...) 的结果在最后一步中乘以 5。参见 ?Syntax 优先级 table。

例如下面的例子 y 设置为它的平方根,而不是它的平方根的两倍,因为 y %<>% sqrt 先完成,因为 %<>%* 有更高的优先级] 并且只有在赋值完成后才进行乘法运算。

y <- 1:3
y %<>% sqrt * 2
y

使用点

如果希望避免将其自动插入为第一个参数,则点必须是在 RHS 上传递的函数的参数——如果点只是其表达式之一的表达式的一部分不计算在内的参数 -- 仍将插入点。

例如,

10 %>% sum(.+2)
## [1] 22

10 %>% sum(., .+2) # same

使用 %>%

在下面的所有情况下 x 或等同于 .round 的第一个参数,第二个参数是包含 x 或点的表达式。在 x %>% round(...)

的输出上乘以 5
x <- 1:10 # assumed input

# these are all equivalent

x %>% round((.-2)/5)*5

round(x, (x-2)/5)*5

x %>% round(., (.-2)/5)*5

x %>% round((.-2)/5)*5

(x %>% round(., (.-2)/5)) * 5

大概需要的是这些等效表达式之一:

round((x-2)/5) * 5

x %>% `-`(2) %>% `/`(5) %>% round %>% `*`(5)

x %>% subtract(2) %>% divide_by(5) %>% round %>% multiply_by(5)

x %>% { round((.-2)/5) * 5 }

使用 %<>%

上面的最后两行代码也可以用 %<>% 代替 %>%,例如

x %<>% { round((.-2)/5) * 5 }