在函数中使用 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 具有 >= 符号时,再次出现空 df 问题。这是 dplyr 中的错误还是我做错了什么?