gpt4 book ai didi

r - 为什么我们不能使用 .作为带有 %>% 的匿名函数中的参数

转载 作者:行者123 更新时间:2023-12-04 14:24:29 26 4
gpt4 key购买 nike

有人可以向我解释为什么以下两个指令有不同的输出:

library(plyr)
library(dplyr)
ll <- list(a = mtcars, b = mtcars)
# using '.' as a function parameter
llply(ll, function(.) . %>% group_by(cyl) %>% summarise(min = min(mpg)))
# using 'd' as function parameter
llply(ll, function(d) d %>% group_by(cyl) %>% summarise(min = min(mpg)))

前一种情况显然甚至没有被评估(我认为 summarise 拼写错误: llply(ll, function(.) . %>% group_by(cyl) %>% sumamrise(min = min(mpg))) 不会引发错误)。

所以这与范围规则和评估事物的位置有关,但我真的很想了解发生了什么,以及为什么会发生这种情况?我用 .作为匿名函数中的一个参数,我很困惑地看到结果。

长话短说,为什么 .不适用于 %>% ?

最佳答案

这似乎是因为 . 的特殊用途作为使用管道时的占位符。来自 ?"%>%" :

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)).

关于r - 为什么我们不能使用 .作为带有 %>% 的匿名函数中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40217444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com