使用 rlang 和 tidyeval 在函数内部的当前方式

huangapple go评论94阅读模式
英文:

Current way to use rlang and tidyeval inside functions

问题

只是想知道在函数内部使用 tidyeval 原则的当前最佳实践是什么。

假设我们在环境中有两个 tibble,并且我们想将它们的名称传递给 purrr::map 调用:

  1. library(tidyverse)
  2. t1 <- tribble(
  3. ~name,
  4. "foo"
  5. )
  6. t2 <- t1

要通过引用它们的名称作为字符串来打印 t1t2,可以使用以下方法:

  1. ls() %>%
  2. map(
  3. ~get(.x)
  4. )

但是我尝试更符合惯用法的 tidyeval 方法却不起作用:

  1. ls() %>%
  2. map(
  3. ~{{.x}}
  4. )
  5. ls() %>%
  6. map(
  7. ~enquo(.x)
  8. )
  9. ls() %>%
  10. map(
  11. ~sym(.x)
  12. )

所有这些都会打印对象的名称,而不是它们的内容。

如何使用 tidyeval 方法使其起作用呢?

英文:

Just wondering what the current start of the art is for using tidyeval principles inside a function.

Imagine we have two tibbles in our environment, and we want to pass their names to a purrr::map call:

  1. library(tidyverse)
  2. t1 &lt;- tribble(
  3. ~name,
  4. &quot;foo&quot;
  5. )
  6. t2 &lt;- t1

To print t1 and t2 via references to their names as strings, this works:

  1. ls() %&gt;%
  2. map(
  3. ~get(.x)
  4. )

ut my attempt at more idiomatically tidyeval approaches don't

  1. ls() %&gt;%
  2. map(
  3. ~{{.x}}
  4. )
  5. ls() %&gt;%
  6. map(
  7. ~enquo(.x)
  8. )
  9. ls() %&gt;%
  10. map(
  11. ~sym(.x)
  12. )

These all print the objects' names, not their contents.

How does this working using the tidyeval approach?

答案1

得分: 2

你需要使用 eval() 来评估这些符号

  1. ls() %>%
  2. map(
  3. ~eval(sym(.x))
  4. )

请注意,这种方法只适用于 sym()。因此,根据你想要做的事情,你可能需要找到一种评估其他捕获表达式的方法。

英文:

you need to use eval() to evaluate the symbols

  1. ls() %&gt;%
  2. map(
  3. ~eval(sym(.x))
  4. )

Note this way only works with sym(). so depending on what you want to do you might have to find a way to evaluate the other captured expressions.

huangapple
  • 本文由 发表于 2023年2月24日 02:56:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549174.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定