One error you may encounter in R is:
Error: attempt to apply non-function
This error usually occurs when you attempt to multiply values in R but forget to include a multiplication (*) sign.
This tutorial shares exactly how to handle this error in two different scenarios.
Scenario 1: Resolve Error in Data Frame Multiplication
Suppose we create the following data frame in R:
#create data frame
df <- data.frame(x=c(1, 2, 6, 7),
y=c(3, 5, 5, 8))
#view data frame
df
x y
1 1 3
2 2 5
3 6 5
4 7 8
Now suppose we attempt to create a new column that is equals to column x multiplied by 10:
#attempt to create new column
df$x_times_10 <- df$x(10)
Error: attempt to apply non-function
We receive an error because we forgot to include a multiplication (*) sign.
To resolve this error, we must include a multiplication sign:
#create new column
df$x_times_10 <- df$x*(10)
#view updated data frame
df
x y x_times_10
1 1 3 10
2 2 5 20
3 6 5 60
4 7 8 70
Scenario 2: Resolve Error in Vector Multiplication
Suppose we create two vectors in R and attempt to multiply together their corresponding elements:
#create two vectors
x <- c(1, 2, 2, 2, 4, 5, 6)
y <- c(5, 6, 8, 7, 8, 8, 9)
#attempt to multiply corresponding elements in vectors
(x)(y)
Error: attempt to apply non-function
We receive an error because we did not include a multiplication sign.
To resolve this error, we must include a multiplication sign:
#multiply corresponding elements in vectors
(x)*(y)
[1] 5 12 16 14 32 40 54
Notice that no error is produced this time.
Additional Resources
The following tutorials explain how to fix other common errors in R:
How to Fix: the condition has length > 1 and only the first element will be used
How to Fix: non-numeric argument to binary operator
How to Fix: dim(X) must have a positive length
How to Fix: error in select unused arguments