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