如何用dplyr和dot elipse编写嵌套函数?

pie*_*ito 7 nested r dplyr nse

我想尽量简单

一些样本数据:

library(magrittr)
library(dplyr)
library(rlang)

# sample data
tib <- tibble(
  a = 1:3,
  b = 4:6,
  c = 7:9
)
Run Code Online (Sandbox Code Playgroud)

现在是一个使两列总和的函数:

foo = function(df, x, y) {

  x <- enquo(x)
  y <- enquo(y)

  df %>% 
   select( !! x, !! y) %>% 
   mutate(sum = !! x + !! y) 
}
Run Code Online (Sandbox Code Playgroud)

希望它有效:

foo(tib, a, b) # to show it works

# A tibble: 3 x 3
#       a     b   sum
#   <int> <int> <int>
# 1     1     4     5
# 2     2     5     7
# 3     3     6     9
Run Code Online (Sandbox Code Playgroud)

现在我想用非固定数量的参数编写第二个函数,该函数调用foo所有可能的参数对:

foo.each(tib, a, b, c) 
# calls foo(tib, a, b)
# calls foo(tib, a, c)
# calls foo(tib, b, c)
# i.e calls foo for each possible pair
Run Code Online (Sandbox Code Playgroud)

我试过这个,但这不起作用:

foo.each = function(df, ...) {
  args <- sapply(substitute(list(...))[-1], deparse)
  args

  nb.args <- args %>% length
  for (i in nb.args:2)
    for (j in 1:(i - 1))
      foo(df, args[i], args[j]) %>% print
}
Run Code Online (Sandbox Code Playgroud)

问题在于foo:

   mutate(sum = !! x + !! y) 
Run Code Online (Sandbox Code Playgroud)

我认为它被评估为:

  mutate(sum = args[i] + args[j])
Run Code Online (Sandbox Code Playgroud)

我尝试过很多东西,包括使用rlang::quos但我厌倦了它,我需要你的帮助.


编辑:克里斯发现了一个聪明而简单的技巧来纠正我的foo.each功能....在这种情况下,是否有更自然的方法来处理elipse?

例如,有一种更好的方法来获得args函数的开头而不是:

  args <- sapply(substitute(list(...))[-1], deparse)
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 4

您的foo函数期望将变量名称传递给它,而您试图将args[i]字符串传递给它。

结合使用sym和取消引用!!就可以达到目的:

foo.each = function(df, ...) {
  args <- sapply(substitute(list(...))[-1], deparse)
  args

  nb.args <- args %>% length
  for (i in nb.args:2)
    for (j in 1:(i - 1))
      foo(df, !!sym(args[i]), !!sym(args[j])) %>% print
}
Run Code Online (Sandbox Code Playgroud)