如何将'...'参数传递给lazyeval中的interp()公式

时间:2016-06-14 15:11:24

标签: r lazy-evaluation nse lazyeval

我正在尝试进行一些参数化dplyr操作。表达问题根源的最简单可重复的例子是:

# Data
test <- data.frame(group = rep(1:5, each = 2),
                   value = as.integer(c(NA, NA, 2, 3, 3, 5, 7, 8, 9, 0)))

> test
    group value
1      1    NA
2      1    NA
3      2     2
4      2     3
5      3     3
6      3     5
7      4     7
8      4     8
9      5     9
10     5     0 

# Summarisation example, this is what I'd like to parametrise
# so that I can pass in functions and grouping variables dynamically

test.summary <- test %>% 
                group_by(group) %>% 
                summarise(group.mean = mean(value, na.rm = TRUE))

> test.summary
Source: local data frame [5 x 2]

    group group.mean
    <int>      <dbl>
1     1        NaN
2     2        2.5
3     3        4.0  # Correct results
4     4        7.5
5     5        4.5

这是我独自走多远

# This works fine, but notice there's no 'na.rm = TRUE' passed in

doSummary <- function(d_in = data, func = 'mean', by = 'group') {
# d_in: data in
# func: required function for summarising
# by:   the variable to group by 
# NOTE: the summary is always for the 'value' column in any given dataframe

    # Operations for summarise_
    ops <- interp(~f(value), 
                  .values = list(f = as.name(func),
                                 value = as.name('value')))        
    d_out <- d_in %>% 
             group_by_(by) %>% 
             summarise_(.dots = setNames(ops, func))
}

> doSummary(test)
Source: local data frame [5 x 2]

  group mean(value)
  <int>       <dbl>
1     1          NA
2     2         2.5
3     3         4.0
4     4         7.5
5     5         4.5

尝试使用'na.rm'参数

# When I try passing in the 'na.rm = T' parameter it breaks
doSummary.na <- function(d_in = data, func = 'mean', by = 'group') {
    # Doesn't work
    ops <- interp(~do.call(f, args), 
                  .values = list(f = func,
                                 args = list(as.name('value'), na.rm = TRUE)))

    d_out <- d_in %>% 
             group_by_(by) %>% 
             summarise_(.dots = setNames(ops, func))
}

> doSummary.na(test)
Error: object 'value' not found 

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:3)

您的标题提及...,但您的问题却没有。如果我们不需要处理...,那么答案会更容易 ,因为我们根本不需要do.call,我们可以直接调用该函数;只需将您的ops定义替换为:

ops = interp(~f(value, na.rm = TRUE),
             f = match.fun(func), value = as.name('value'))

请注意,我在这里使用了match.fun而不是as.name。这通常是一个更好的主意,因为它与函数查找“就像R”一样工作。因此,您不能只将函数名称字符作为参数传递,还可以传递函数名称或匿名函数:

doSummary.na(test, function (x, ...) mean(x, ...) / sd(x, ...)) # x̂/s?! Whatever.

说到这一点,您尝试设置列名也会失败;您需要将ops放入列表中以解决此问题:

d_in %>%
    group_by_(by) %>%
    summarise_(.dots = setNames(list(ops), func))

...因为.dots需要一个操作列表(而setNames也需要一个向量/列表)。但是,如果您将func对象传递给不是字符向量的函数,则此代码将再次无效。为了使其更加健壮,请使用以下内容:

fname = if (is.character(func)) {
        func
    } else if (is.name(substitute(func))) {
        as.character(substitute(func))
    } else {
        'func'
    }

d_in %>%
    group_by_(by) %>%
    summarise_(.dots = setNames(list(ops), fname))

如果你真的想允许传递...而不是已知的参数,事情变得更复杂,因为(据我所知),没有直接的方式通过...传递interp和你一样,我无法让do.call方法起作用。

包提供了非常好的函数make_call,它可以帮助我们找到解决方案。以上也可以写成

# Not good. :-(
ops = make_call(as.name(func), list(as.name('value'), na.rm = TRUE))

这很有效。仅当func作为字符向量传递时,。如上所述,这根本不灵活。

但是,make_call只包含基础R的as.call,我们可以直接使用它:

ops = as.call(list(match.fun(func), as.name('value'), na.rm = TRUE))

现在我们可以简单地传递...

doSummary = function (d_in = data, func = 'mean', by = 'group', ...) {
    ops = as.call(list(match.fun(func), as.name('value'), ...))

    fname = if (is.character(func)) {
            func
        } else if (is.name(substitute(func))) {
            as.character(substitute(func))
        } else {
            'func'
        }

    d_in %>%
        group_by_(by) %>%
        summarize_(.dots = setNames(list(ops), fname))
}

要明确:使用interp可以实现同样的效果,但我认为这需要从列表中手动构建formula对象,这与我的解决方案中的操作非常相似,然后(冗余地)在结果上调用interp

我通常发现虽然非常优雅,但在某些情况下,基础R提供了更简单的解决方案。特别是,interp是一个强大的substitute替换,但是bquote,一个相当不充分的基本R函数,已经提供了许多相同的语法优势。与基本R表达式不同,对象的巨大好处是它们随身携带它们的评估环境。但是,并不总是需要这样做。