测试
select_if()
函数的功能很有趣,特别是学习如何将多个条件捆绑在一起以进行列选择。
例如,我可以通过此类代码选择具有超过 x 级别的因素
iris %>% select_if(~is.factor(.) & nlevels(.) > 2) %>% names
[1] "Species"
但是当我尝试使用其中一个字符串匹配函数时,它不起作用
iris %>% select_if(~is.numeric(.) & ends_with("Length")) %>% names
Error:
! `ends_with()` must be used within a *selecting* function.
ℹ See ?tidyselect::faq-selection-context for details.
select_if()
函数的帮助指出“像starts_with()、contains()或matches()这样的函数是仅在选择上下文中工作的选择帮助器,例如dplyr::select()或tidyr::的cols参数枢轴_更长()“
但是
select_if
不是一个选择上下文吗?
非常感谢任何帮助或解决方案
这是
select(all_of(...))
内部的基本 R 组合,似乎有效,但可能存在边缘情况,不同的方法效果更好。
iris %>% select(all_of(names(iris)[sapply(iris, \(x) nlevels(x)) > 2]))