In R, if you are missing mathematical operators when performing mathematical operations, you can raise the error: attempt to apply non-function. This error occurs because the R interpreter expects a function whenever you place parentheses () after a variable name.

You can solve this error by checking your code for missing operators and including them, for example,

3 (4 ^ 2)

becomes

3 * (4 ^2)

This tutorial will go through the error in detail and how to solve it with code examples.


Parentheses in R

We use parentheses (also known as round brackets) primarily to call a function in R. Every function call requires the use of parentheses. Therefore if you place parentheses after a variable that is not a function, the R interpreter will try to call the non-function and then raise the error: attempt to apply non-function. For example:

2()
Error: attempt to apply non-function

Example

Let’s look at an example of a program that calculates the profit made from a bakery. The formula for calculating profit is amount_sold * (price - cost). In this case, the bakery sold 40 cakes

price = 4.99
cost = 1.40
profit = 40(price - cost)

Let’s run the code to see what happens:

Error: attempt to apply non-function

The error occurs because we are missing the * between the two terms in the mathematical expression. Therefore R is interpreting 40(price – cost) as a function call, where the function has the name 40.

Solution

We can solve this error by putting the * between the two terms in the expression. Let’s look at the revised code:

price = 4.99
cost = 1.40
profit = 40 * (price - cost)
profit
[1] 143.6

The bakery made £143.60 profit!

Summary

Congratulations on reading to the end of this tutorial! Generally, this error occurs when you put parentheses after a non-function like a number. You can solve this error by double-checking your code for missing mathematical operators.

For further reading on R related errors, go to the articles: 

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!