Tabulating a column after a pipe command


I am trying to tabulate the Species column after subsetting the data using the pipe function, but this is not working and returning the following error:

iris %>% select(Species, Sepal.Length) %>% table(Species)
Error in table(., Species) : object 'Species' not found

Please let me know if you can suggest what I am doing wrong in it.

Thank you.

table() isn't part of tidyverse. Try

z <- iris %>% select(Species, Sepal.Length)

Hi Startz,

Thank you for the explanation. I was just interested in running the table in the same command. I could print the head of the df: iris %>% select(Species, Sepal.Length) %>% head()

So I was wondering why the table function is not applicable in the same way.

It might help to read up on the with( ) function from base R.

A tidy function expects a data frame as the first argument and then operates on specified variables from that data frame. The pipe passes data on the LHS (left hand side) of the pipe to the first argument of the function on the RHS (right hand side). The table function does not work this way. If you give it a data frame it will use all of the variables, as in the mtcars example below. If all you want is the output from table(iris$Species) but using pipes, then pass it a data frame with just Species selected.


# the issue is what gets passed to the table() function

# note: both base pipe (|>) and magrittr pipe (%>%) will work

# the 2nd pipe passes a data frame with just one iris variable to table()
iris |> select(Species) |> table()    
#> Species
#>     setosa versicolor  virginica 
#>         50         50         50

# the 2nd pipe passes a data frame with two mtcars variables to table()                              
mtcars |> select(cyl, am) |> table()  
#>    am
#> cyl  0  1
#>   4  3  8
#>   6  4  3
#>   8 12  2

# pipes the entire iris data frame to with(), which makes the iris variables available to table()
iris |> with(table(Species))         
#> Species
#>     setosa versicolor  virginica 
#>         50         50         50

# the 2nd pipe passes a variable pulled from the iris data frame (like iris$Species) to table()
iris |> pull(Species) |> table()
#>     setosa versicolor  virginica 
#>         50         50         50

Created on 2022-10-01 with reprex v2.0.2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.