0

I was curious why the code below can not run. I thought the dot . ia a palceholder and pass mtcats to the position.

table(mtcars$cyl)

mtcars %>% table(.$cyl)

zhiwei li
  • 1,635
  • 8
  • 26
  • 2
    Use `{}` as explained here [Using the %>% pipe, and dot (.) notation](https://stackoverflow.com/questions/42385010/using-the-pipe-and-dot-notation) – arg0naut91 Mar 21 '20 at 07:52
  • hi please try this hope this will help.```mtcars %>% { table(mtcars$cyl) }``` as mention in above comments. – Tushar Lad Mar 21 '20 at 08:02

1 Answers1

1

The pipe %>% pastes the object on the left as the first argument into the function on the right. So you basically execute:

table(mtcars, mtcars$cyl)
#> Error in table(mtcars, mtcars$cyl): all arguments must have the same length

As agr0naut91 comments, this can be fixed with using curly brackets:

library(magrittr)

mtcars %>% {table(.$cyl)}
#> 
#>  4  6  8 
#> 11  7 14

This works whenever you want to pipe into a function that is not pipe friendly, which usually means that it doesn’t have a data.frame argument as the first argument. Using dplyr::count() you can get an output that is comparable to base::table(), without having to use the curly brackets.

library(dplyr, warn.conflicts = FALSE)

mtcars %>% count(cyl)
#> # A tibble: 3 x 2
#>     cyl     n
#>   <dbl> <int>
#> 1     4    11
#> 2     6     7
#> 3     8    14
Till
  • 3,845
  • 1
  • 11
  • 18