我想测试数据框的列数是否与预期的列数匹配。代码应适合 tidyverse 管道。
但是,这段代码不起作用:
library(tidyverse)
# does not work:
mtcars %>%
select_if(negate(is.numeric)) %>%
if(ncol(.) > 0) stop("there should be no non-numeric column!")
#> Error in if (.) ncol(.) > 0 else stop("there should be no non-numeric column!"): argument is of length zero
# does work:
mtcars2 <- mtcars %>%
select_if(negate(is.numeric))
if(ncol(mtcars2) > 0) stop("there should be no non-numeric column!")
由 reprex package 创建于 2019-09-29 (v0.3.0)
ncol()
似乎没有正确评估/支持“点”(.)。
是否有(直接的)方法来测试 tidyverse-pipeline 样式中的列数?
最佳答案
我不确定你到底想做什么,但为了让你的代码在当前流程中工作,你可以用大括号括起你的 if
block :
library(dplyr)
mtcars %>%
select_if(negate(is.numeric)) %>%
{if(ncol(.) > 0) stop("there should be no non-numeric column!")}
关于r - 测试 tidyverse 中的列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58153502/