2

我有以下内容data.table

dtable <- data.table(column1 = c(1, 2, 3, 5, 6, 7, 8),
                     column2 = c(1, 1, 1, 5, 5, 6, 8),
                     column3 = c(7, 8, 9, 0, 9, 2, 3))

我想做类似以下功能的东西,但是在参数化函数中:

dtable %>% 
  dplyr::group_by(column1) %>% 
  dplyr::summarise(Result = ifelse(column1 == column2, "A", "B"))

为此,我创建了以下函数:

Test <- function(.df, .columnName, .columnToGroup){
  res <- .df %>%
    # This line is interpreted correctly
    dplyr::group_by_(lazyeval::interp(.columnToGroup, .columnToGroup = as.name(.columnToGroup))) %>%

    # This line does not interpret the == condition as a logical one
    dplyr::summarise_(Result = ifelse((lazyeval::interp(.columnToGroup == .columnName,
                                                        .columnToGroup = as.name(.columnToGroup),
                                                        .columnName = as.name(.columnName))),
                                      "A", "B"))
  return(res)
}

我将非标准评估函数 (group_by_summarise_) 与lazyeval::interp函数结合使用,但==条件没有以正确的方式解释,并且出现以下异常:

Test(dtable, "column1", "column2")

 Error in UseMethod("interp") : 
  no applicable method for 'interp' applied to an object of class "logical"

我尝试了许多不同的组合(quote, expr_env,as.lazy等),但都没有成功。感谢这个伟大的非标准评估指南,我之前能够使用这些lazyeval函数来评估算术表达式,但我找不到让它们解释这段代码中的逻辑条件的方法。

任何帮助将不胜感激。

4

1 回答 1

1

使用ifelse,我们可以尝试(在评论中使用 @docendodiscimus list

Test <- function(.df, .columnName, .columnToGroup){
 .df %>%   
   dplyr::group_by_(.dots = .columnToGroup )%>%
            dplyr::summarise_(.dots =

                            setNames(list(lazyeval::interp(quote(ifelse(colGrp == colName,
                               "A", "B")), .values = list(colGrp = as.name(.columnToGroup),
                                                    colName = as.name(.columnName)))),
                                  "Result"))

 }

res2 <- Test(dtable, "column2", "column1")
identical(res1, res2)
#[1] TRUE

“res1”在哪里

res1 <- dtable %>% 
          dplyr::group_by(column1) %>% 
          dplyr::summarise(Result = ifelse(column1 == column2, "A", "B"))

更新

使用新版本的dplyrie 0.6.0(等待 2017 年 4 月发布),我们还可以在group_by和中取消引用summarise。该enquo函数的作用与substitutefrom类似base R_ _quosure!!UQgroup_bysummarise

Test1 <- function(df, colN, colGrp){
      colN <- enquo(colN)
      colGrp <- enquo(colGrp)

      df %>% 
         group_by(!!colGrp) %>%
         summarise(Result = if_else((!!colGrp) == (!!colN), "A", "B"))
}

res3 <- Test1(dtable, column2, column1)
identical(res2, res3)
#[1] TRUE
于 2017-04-10T14:22:46.480 回答