Select Page

# How to Solve R Error: attempt to apply non-function

by | Programming, R, Tips

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`