Fixing R Errors: error in unique.default(x, nmax = nmax) : unique() applies only to vectors

While error messages are a part of the programming process, they can be even more annoying when they come across as complete gibberish. This problem is even worse when it still looks like gibberish after you learn what is going on. The “error in unique.default(x, nmax = nmax) : unique() applies only to vectors” error message is one of these monsters. What makes it worse is that it has a really simple cause. However, it has an easy solution as well.

The circumstances of this error.

This error message occurs when using the ave() function. It specifically occurs when improperly defining the averaging function. The reason this causes the error is not obvious and the error message does not help.

> x = c(1,2,3,4,5)
> ave(x, mean)
Error in unique.default(x, nmax = nmax) :
unique() applies only to vectors

This simple example shows a couple of lines of code, which produce this error message. The error does not result from the complexity of the program but rather from an inaccurate entry of this function’s arguments. You are more likely to make this mistake when coming to R from other languages and are not yet familiar with some of its quirks.

What is causing this error?

What is causing this error is the fact that the averaging function argument is the third argument in the ave() function and not the second. If you are going to use it as the second argument, you need to use the “FUN = formula” format to define the averaging formula. Otherwise, it will think you are entering the second argument.

> x = c(1,2,3,4,5)
> ave(x, FUN = mean)
[1] 3 3 3 3 3

In this example, we have the ave() function setting the averaging function properly. In this case, it is being set to “mean” and thereby producing the mean value of the x vector.

> x = c(1,2,3,4,5)
> ave(x)
[1] 3 3 3 3 3

In this example, the averaging function is simply unused and there is no error message. This clearly traces down the source of the error message to the averaging formula.

How to fix this error.

There are two ways of correcting this error. The first involves removing the average averaging formula. This only works if you are calculating mean value, because that is the default. The second approach involves producing the correct form of the averaging formula.


This is the simplest fix of this error because it uses the default averaging formula. It is a simple solution if you are looking for the mean value of the vector argument.

ave(x, mean)
ave(x, FUN = mean)

This approach to fixing the problem works regardless of the averaging formula you are using. It involves making sure that the argument is formatted properly by adding “FUN =” in front of the averaging formula. In both cases, the error is fixed but only the second one will fix it for every averaging formula you might use.