This error occurs when we try to use the ave()
function without specifying the FUN
argument.
We can solve this error by specifying the FUN
argument explicitly. For example,
average <- ave(data$x, data$group, FUN=mean)
This tutorial will go through the error in detail and how to solve it with code examples.
Example
Let’s look at an example to reproduce the error. First, we will create a data frame.
data <- data.frame(x = sample(1000,12), # Create example data frame group = rep(letters[1:6], each = 2)) data
x group 1 363 a 2 292 a 3 44 b 4 130 b 5 208 c 6 938 c 7 440 d 8 832 d 9 639 e 10 386 e 11 905 f 12 33 f
Next, we will try to get the average value for each group in the data frame using the ave()
function. In order to average over the groups, we need to provide the grouping variable data$group
.
average <- ave(data$x, data$group, mean) average
Let’s run the code to see the result:
Error in unique.default(x, nmax = nmax) : unique() applies only to vectors
The error occurred because we did not specify the FUN argument explicitly when calling the ave() function.
Solution
We can solve this error by specifying the FUN
argument. We want to calculate the average across the groups, therefore we need the mean
function. Let’s look at the revised code:
average <- ave(data$x, data$group, FUN=mean) average
Let’s run the code to get the average across the groups in the data frame as a numeric vector.
[1] 327.5 327.5 87.0 87.0 573.0 573.0 636.0 636.0 512.5 512.5 469.0 469.0
Summary
Congratulations on reading to the end of this tutorial!
For further reading on R-related errors, go to the articles:
- How to Solve R Error: mapping should be created with aes() or aes_()
- How to Solve R Error: Could not find function “%”
- How to Solve R Error in cov.wt(z) : ‘x’ must contain finite values only
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 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.