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!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!