参见下面的代码行; 谋杀是一个数据框,其中包含变量/列总数、人口和比率:
r <- murders %>% summarize (rate = sum(total) / sum(population) * 10^6) %>% .$rate
在这种情况下,运算符%>%.$
是如何工作的?有人可以详细说明吗?
编辑:我知道这行代码的结果(它正在提取 rate 列),但想知道为什么或如何发生,因为通常, %>%
后面跟着一个函数,即使我们将 $
运算符视为函数,它也不会在 %>%
之后开始,而是有一个 .
之间。如果我们说 .
是 $
函数中 %>%
输出的占位符,那么 %>%$
也应该可以工作,因为 %>%
的输出默认情况下自动进入 RHS 函数的第一个参数(在我们的例子中是 $
)在这种情况下不需要 .
。
最佳答案
在这种情况下,相当于拉
最小示例
从一个实际运行的最小工作示例开始就很好了。我建议在后续问题中至少提供这么多内容。
library(dplyr)
murders <- data.frame('loc'=c('A','B','C'),
'population'=c(10,20,30),
'total'=c(2,3,5))
result <- murders %>%
summarize (rate = sum(total) / sum(population) * 10^6) %>%
.$rate
result # 166666.7
上例中的 .
是 result of the previous pipe 。美元符号是一个提取运算符,它返回名为“rate”的列。
等效示例
pull 函数将管道的结果传递到第一个参数中。由于在本例中,pull 将执行与 extract ($
) 相同的操作,因此所发生的情况更加明确。
result_2 <- murders %>%
summarize (rate = sum(total) / sum(population) * 10^6) %>%
pull(rate)
result_2 # 166666.7
您可以通过执行以下操作来说明这一点
result_3 <- murders %>%
summarize (rate = sum(total) / sum(population) * 10^6) %>%
pull(.data=., var=rate)
result_3 # 166666.7
管道到 $
或 [[
将不起作用
短篇小说,$
和 [[
是原语,magrittr %>%
works with functions .
Pipe an object forward into a function or call expression.
lhs %>% rhs
Arguments lhs
A value or the magrittr placeholder. rhs
A function call using the magrittr semantics.
`$` # .Primitive("$")
`[[` # .Primative{"[[")
近似函数pull
或getElement
是函数
`getElement`
# function (object, name)
# {
# if (isS4(object))
# methods::slot(object, name)
# else object[[name, exact = TRUE]]
# }
# <bytecode: 0x5618b3018358>
# <environment: namespace:base>
关于r - 'pipe' 、 'dot' 和 'dollar' 运算符的串联似乎在 R 中起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59516684/