如何在R中修复错误:试图应用非函数

963 阅读1分钟

你在R中可能遇到的一个错误是:

Error: attempt to apply non-function

这个错误通常发生在你试图在R中进行数值相乘,但却忘记了包括一个乘号(*)。

本教程准确地分享了如何在两种不同的情况下处理这个错误。

情景1:解决数据帧乘法的错误

假设我们在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

现在假设我们试图创建一个新的列,等于列x乘以10:

#attempt to create new column
df$x_times_10 <- df$x(10)

Error: attempt to apply non-function

我们收到了一个错误,因为我们忘记了包括一个乘法(*)符号。

为了解决这个错误,我们必须包括一个乘号:

#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

情景2:解决向量乘法中的错误

假设我们在R中创建了两个向量,并试图将它们的相应元素相乘:

#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

我们收到一个错误,因为我们没有包括一个乘号。

为了解决这个错误,我们必须包含一个乘法符号:

#multiply corresponding elements in vectors
(x)*(y)

[1]  5 12 16 14 32 40 54

注意,这次没有产生错误。

其他资源

下面的教程解释了如何修复R中的其他常见错误:

如何修复:条件的长度>1,只有第一个元素会被使用
如何修复:二进制运算符的非数字参数
如何修复:dim(X)必须有一个正的长度
如何修复:选择未使用参数的错误