我有以下内容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
函数来评估算术表达式,但我找不到让它们解释这段代码中的逻辑条件的方法。
任何帮助将不胜感激。