R中filter结合if_any与starts_with传入无效列名为何返回全量数据?
关于dplyr中if_any()筛选不存在列时返回全量数据的疑问与解决方案
在R中使用dplyr::filter()结合dplyr::if_any()进行数据筛选时,发现当传入数据框中不存在的列名(如下方最后两个示例),会返回整个数据框,这似乎不符合预期——难道不该返回行数为0的数据框吗?
示例代码
library(dplyr) nrow(iris) # = 150 iris %>% filter(if_any(starts_with("Sepal"), ~ . > 6)) %>% nrow() # = 61 iris %>% filter(if_any(starts_with("nonsense"), ~ . > 5)) %>% nrow() # = 150 iris %>% filter(if_any(starts_with("nonsense"), ~ . == "more_nonsense")) %>% nrow() # = 150
我猜测这种行为存在底层原因,但仍想知道能否在代码中添加额外安全措施,比如提示用户当前数据框中没有以“nonsense”开头的列?
更新 - 尝试的自定义解决方案
我对自定义函数经验不足,但尝试写出了以下代码,不确定是否合理?
if_any2 <- function(data, string, helper, ...) { stopifnot( "No columns found in data with the supplied helper function" = select(data, helper(string, ignore.case=FALSE)) %>% ncol() >= 1 ) if_any(.cols = helper(string, ignore.case=FALSE), ...) } iris %>% filter(if_any2(data = ., string = "Sepal", helper = starts_with, ~ . == 6.3 | . == 2.8)) %>% nrow() # = 22
内容的提问来源于stack exchange,提问作者user167591
相关产品推荐
相关产品推荐

