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

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

Current way to use rlang and tidyeval inside functions

问题

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

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

library(tidyverse)

t1 <- tribble(
  ~name,
  "foo"
)

t2 <- t1

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

ls() %>%
  map(
    ~get(.x)
  )

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

ls() %>%
  map(
    ~{{.x}}
  )

ls() %>%
  map(
    ~enquo(.x)
  )

ls() %>%
  map(
    ~sym(.x)
  )

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

如何使用 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:

library(tidyverse)

t1 &lt;- tribble(
  ~name,
  &quot;foo&quot;
  )

t2 &lt;- t1

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

ls() %&gt;% 
  map(
    ~get(.x)
    )

ut my attempt at more idiomatically tidyeval approaches don't

ls() %&gt;% 
  map(
    ~{{.x}}
  )

ls() %&gt;% 
  map(
    ~enquo(.x)
  )


ls() %&gt;% 
  map(
    ~sym(.x)
  )

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

How does this working using the tidyeval approach?

答案1

得分: 2

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

ls() %>% 
    map(
        ~eval(sym(.x))
    )

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

英文:

you need to use eval() to evaluate the symbols

ls() %&gt;% 
    map(
        ~eval(sym(.x))
    )

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:

确定