How to Solve R Error in n(): Must be used inside dplyr verbs

by | Programming, R, Tips

This error occurs when you try to call the n() function from the dplyr package but already have plyr loaded after loading dplyr. Both packages have the functions summarise() or summarize() which use n().

You can solve the error by using the “package::function” syntax.

This tutorial will go through how to solve the error with code examples.


Table of contents

Example

Let’s look at an example of using the n() function. The n() function is implemented specifically for each data source. We can only use the function within summarize(), mutate(), and filter().

library(dplyr)
library(plyr)

mtcars %>%

    group_by(cyl) %>%
    
summarize(count = n())

Let’s run the code to see what happens:

Error in `n()`:
! Must be used inside dplyr verbs.
Run `rlang::last_error()` to see where the error occurred.

The error occurs because we attempted to use the summarize() function from dplyr to count the number of entries under each cyl group. However, we loaded the plyr package after the dplyr package, which causes a conflict as both packages have the summarize function.

Solution

We can solve the error by using the “package::function” syntax, in this case dplyr::summarize. Using this syntax ensures that R knows exactly from which package to import the summarize() function. Let’s look at the revised code:

library(dplyr)
library(plyr)

mtcars %>%

    group_by(cyl) %>%

    dplyr::summarize(count = n())

Let’s run the code to get the result:

# A tibble: 3 × 2
    cyl count
  <dbl> <int>
1     4    11
2     6     7
3     8    14

Summary

Congratulations on reading to the end of this tutorial!

For further reading on R related errors, go to the article:

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨