r - 测试 tidyverse 中的列数

标签 r testing tidyverse

我想测试数据框的列数是否与预期的列数匹配。代码应适合 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/

相关文章:

r - 按列将多个函数应用于两个数据框

c# - 将 C# 代码转换为 R 以将表转换为向量

r - 使用 dplyr 过滤 "either" "or"

根据基线特征从队列研究数据中删除个体

angularjs - 当我在 Controller 中注入(inject) ui-router resolve 时,Karma 测试失败

r - 在函数中使用嵌套变量

r - 在 R 中拟合非线性朗缪尔等温线

r - 在 R 中推送和弹出列表的更好方法?

testing - 无法在集成测试中访问 Sails.js 应用程序实例

c# - HttpClient - 不接受 DNS 更改