Error: attempt to apply non-function

Simple English Explanation

This error message really needs to be renamed. When you see this, walk through your formulas around the location of the error message. Ninety nine percent of the time you’re looking at a basic syntax issue with how you are laying out your calculations in your code.

One of your calculations, likely one which uses brackets to break up your order of operations, is missing an operator somewhere in the code. There is a significant difference in how R handles the following two statements, identical except for a single character.

  • profit = units * (unit_price – unit_cost)
  • profit = units (unit_price – unit_cost)

In the first example, R will solve for the calculation inside the brackets (price – cost) and multiply it by the value in the variable units. Simple math.

In the second example, since there is no * to identify what operation to pursue, R interprets the whole thing as a function call. Solve for the difference between price and cost and apply the function that is named units to transform the result.

Except of course, there is no function named units. But there is an object named units. So what the heck, lets apply THAT to the value in question. So a very confused variable (units) which is most definitely NOT an R function (not even close!) is suddenly “applied” (Dr. Evil air quotes) to the value we fed it.

At which point the program realizes it is trying to do completely unnatural things to an innocent little variable and throws an error: attempt to apply non-function.

SIGH. And this is why we can’t have nice things.

How To Fix “Attempt to apply non-function”

Joking aside, this one is straight forward. Look at your calculations with a fine toothed comb, paying close attention to any situation where you use brackets. Make sure you separate those bracketed items from other elements of the calculation with an appropriate operator (+, -, %, *, other operators).

R needs to chill on this error message. This is basically a syntax error.