%>%.$column_name等效于R基管>
我经常使用 dplyr 管道将一列从 tibble 转换为向量,如下所示
iris %>% .$Sepal.Length
iris %>% .$Sepal.Length %>% cut(5)
如何使用最新的 R 内置管道符号执行相同操作 |>
iris |> .$Sepal.Length
iris |> .$Sepal.Length |> cut(5)
Error: function '$' not supported in RHS call of a pipe
回答
我们可以使用getElement().
iris |> getElement('Sepal.Length') |> cut(5)
- 或 `iris |> with(Sepal.Length)`
回答
在基管中,没有为管道中传递的数据提供占位符。这是magrittr管道和基础 R 管道之间的一个区别。您可以使用匿名函数来访问该对象。
iris |> {(x) x$Sepal.Length}()
- @jpdugo17 The only differences are that `{}` can contain multiple expressions (separated by newline or, `;`), and that it preserves a value's auto-printing visibility. … And of course it uses visually distinct delimiters, which can make nested expressions (as in this case) more readable.
回答
$in的直接使用|>目前已禁用。也许一个原因可能是写
iris$Sepal.Length
并不是
library(magrittr)
iris %>% .$Sepal.Length
如果$仍然需要调用(或 |> 中其他禁用的函数),除了创建函数之外的一个选项,类似于@jay-sf 的解决方案,是$通过函数使用::asbase::`$` 或将其放在刹车中($ ):
iris |> (`$`)("Sepal.Length") |> cut(5)
iris |> base::`$`("Sepal.Length") |> cut(5)
#iris |> base::`[[`("Sepal.Length") |> cut(5) #Alternative
#iris |> base::`[`(,"Sepal.Length") |> cut(5) #Alternative
另一种选择是使用奇异的管道 ->.;。有些人称之为笑话,有些人则巧妙地利用了现有的语法。
iris ->.; .$Sepal.Length |> cut(5)
这会.在.GlobalEnv. rm(.)可以用来删除它。或者,它可以在local:
local({iris ->.; .$Sepal.Length |> cut(5)})
在这种情况下,它会在环境中产生两个相同的对象iris,.但只要它们没有被修改,它们就会指向相同的地址。
tracemem(iris)
#[1] "<0x556871bab148>"
tracemem(.)
#[1] "<0x556871bab148>"
- @tpetzoldt At least *g-grothendieck* describes it as [clever use of existing syntax](https://stackoverflow.com/a/65329845/10488504)
- @GKi “clever” ≠ “good”. I hope nobody *actually* recommends using this in practice.