One error you may encounter in R is:
Error in n() : This function should not be called directly
This error usually occurs when you attempt to use the n() function from the dplyr package, but you happen to have the plyr package loaded after the dplyr package.
This tutorial shares exactly how to fix this error.
How to Reproduce the Error
Suppose we have the following data frame in R:
#define data frame
df frame(team=rep(c('A', 'B'), each=5),
points=c(2, 4, 6, 8, 10, 12, 14, 16, 18, 20),
assists=c(4, 7, 11, 16, 22, 29, 38, 49, 63, 80))
#view data frame
df
team points assists
1 A 2 4
2 A 4 7
3 A 6 11
4 A 8 16
5 A 10 22
6 B 12 29
7 B 14 38
8 B 16 49
9 B 18 63
10 B 20 80
Now suppose we attempt to use the summarize() function from dplyr to count the number of rows, grouped by team:
library(dplyr)
library(plyr)
#attempt to count rows by team
df %>%
group_by(team) %>%
summarize(count = n())
Error in n() : This function should not be called directly
We receive an error because we loaded the plyr package after the dplyr package, which causes issues.
How to Fix the Error
The way to fix this error is to simply use dplyr:summarize so that R knows exactly which package you’d like to use the summarize function from:
library(dplyr)
library(plyr)
#count rows by team
df %>%
group_by(team) %>%
dplyr::summarize(count = n())
# A tibble: 2 x 2
team count
1 A 5
2 B 5
Notice that we’re able to count the number of rows grouped by team without any error this time since we used dplyr::summarize to perform the summary.
Additional Resources
The following tutorials explain how to troubleshoot other common errors in R:
How to Fix in R: Error in as.Date.numeric(x) : ‘origin’ must be supplied
How to Fix: Error in stripchart.default(x1, …) : invalid plotting method
How to Fix: Error in eval(predvars, data, env) : object ‘x’ not found