在函数中使用dplyr时遇到问题。当基于quosure进行过滤时,>符号似乎会导致无法返回数据的问题。
例如:
temp_df <- data.frame(
startdate_c = as.Date(c("2011-08-08", "2007-09-01", "2012-01-01", "2012-10-26", "2012-12-01",
"2016-01-01", "2006-06-01", "2009-04-01", "2005-02-09", "2004-08-01")),
enddate_c = as.Date(c("2011-08-14", "2012-09-04", "2014-06-06", "2014-02-28", "2013-04-05",
"2016-12-01", "2008-04-18", "2009-08-16", "2006-04-30", "2007-06-02")))
这是功能的精简版本:
filter_f <- function(df, startdate = NULL, enddate = NULL) {
if(!missing(startdate)) {
start_var <- enquo(startdate)
} else if("startdate_c" %in% names(df)) {
start_var <- quo(startdate_c)
} else {
stop("No valid startdate found")
}
if(!missing(enddate)) {
end_var <- enquo(enddate)
} else if("enddate_c" %in% names(df)) {
end_var <- quo(enddate_c)
} else {
stop("No valid enddate found")
}
df <- df %>%
filter(!!start_var <= as.Date("2011-12-31") &
!!end_var >= as.Date("2011-01-01"))
return(df)
}
预期产出:
startdate_c enddate_c
1 2011-08-08 2011-08-14
2 2007-09-01 2012-09-04
3 2012-01-01 2014-06-06
4 2012-10-26 2014-02-28
5 2012-12-01 2013-04-05
6 2016-01-01 2016-12-01
而是返回一个空数据框。
如果我调整代码并命名结束日期而不是使用quosure,它可以工作:
filter_f2 <- function(df, startdate = NULL, enddate = NULL) {
if(!missing(startdate)) {
start_var <- enquo(startdate)
} else if("startdate_c" %in% names(df)) {
start_var <- quo(startdate_c)
} else {
stop("No valid startdate found")
}
if(!missing(enddate)) {
end_var <- enquo(enddate)
} else if("enddate_c" %in% names(df)) {
end_var <- quo(enddate_c)
} else {
stop("No valid enddate found")
}
df <- df %>%
filter(!!start_var <= as.Date("2011-12-31") &
enddate_c >= as.Date("2011-01-01"))
return(df)
}
创建startdate和enddate quosures的代码是相同的,当我切换过滤器以使startdate具有&gt; =符号时,再次出现空df问题。这是dplyr中的错误还是我做错了什么?
答案 0 :(得分:3)
这是一个操作顺序问题。比较运算符(<=
和>=
)的优先级高于!
运算符。你需要做
df <- df %>%
filter((!!start_var) <= as.Date("2011-12-31") &
(!!end_var) >= as.Date("2011-01-01"))
出于某种原因,quosues似乎有负值?观察
xvar <- quo(x)
quo(!!xvar <= 0)
# ~TRUE
quo(!!xvar >= 0)
# ~FALSE
与...比较
quo((!!xvar) <= 0)
# ~(~x) <= 0
quo((!!xvar) >= 0)
# ~(~x) >= 0
最后(由于我不完全理解的原因)
quo(x) <= 4
# [1] TRUE
quo(x) >= 4
# [1] FALSE
似乎也与公式有关
(~x) <= 2
# [1] TRUE
(~x) >= 2
# [1] FALSE