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
summarize() which use n().
You can solve the error by using the “
This tutorial will go through how to solve the error with code examples.
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
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.
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
Congratulations on reading to the end of this tutorial!
For further reading on R related errors, go to the article:
- How to Solve R Error: non-conformable arguments
- How to Solve R Error: not defined because of singularities
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!
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!