1

I wouls like to test if the number of columns of a data frame match the expected number of columns. The code should fit in a tidyverse pipeline.

However, this code did not work:

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!")

Created on 2019-09-29 by the reprex package (v0.3.0)

In appears that the "dot" (.) is not correctly evaluated/supported by ncol().

Is there a (straightforward) way to test the number of columns within the tidyverse-pipeline style?

Sebastian Sauer
  • 1,555
  • 15
  • 24

1 Answers1

1

I am not sure what exactly you are trying to do but to make your code work in current flow you can surround your if block with curly braces :

library(dplyr)
mtcars %>% 
  select_if(negate(is.numeric)) %>% 
  {if(ncol(.) > 0) stop("there should be no non-numeric column!")}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Here's some documention on pipe forwarding I found useful: https://stackoverflow.com/questions/42385010/using-the-pipe-and-dot-notation/42386886#42386886 – Sebastian Sauer Sep 29 '19 at 08:34