如何修复:没有非遗的参数给min返回Inf

1,690 阅读1分钟

你在R中可能遇到的一个警告信息是:

Warning message:
In min(data) : no non-missing arguments to min; returning Inf 

每当你试图寻找一个长度为零的向量的最小值或最大值时,就会出现这个警告信息。

值得注意的是,这只是一条警告信息,它实际上不会阻止你的代码运行。

然而,你可以使用以下方法之一来完全避免这个警告信息。

方法1:压制警告信息

suppressWarnings(min(data))

方法2:定义一个自定义函数来计算最小或最大值

#define custom function to calculate min
custom_min <- function(x) {if (length(x)>0) min(x) else Inf}

#use custom function to calculate min of data
custom_min(data)

下面的例子显示了如何在实践中使用每种方法。

方法1:抑制警告信息

假设我们试图使用min()函数来寻找一个长度为0的向量的最小值:

#define vector with no values
data <- numeric(0)

#attempt to find min value of vector
min(data)

[1] Inf
Warning message:
In min(data) : no non-missing arguments to min; returning Inf

注意,我们会收到一条警告信息,告诉我们试图寻找一个没有非遗漏参数的向量的最小值。

为了避免这个警告信息,我们可以使用suppressWarnings()函数:

#define vector with no values
data <- numeric(0)

#find minimum value of vector
suppressWarnings(min(data))

[1] Inf

最小值仍然被计算为 "Inf",但这次我们没有收到警告信息。

方法2:定义一个自定义函数

另一种避免警告信息的方法是定义一个自定义函数,只在向量的长度大于0时计算最小值,否则返回 "Inf"值:

#define vector with no values
data <- numeric(0)

#define custom function to calculate min
custom_min <- function(x) {if (length(x)>0) min(x) else Inf}

#use custom function to calculate min
custom_min(data)

[1] Inf

注意,最小值被计算为 "Inf",我们没有收到警告信息。

其他资源

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

如何在R中修复:dim(X)必须有正的长度
如何在R中修复:名称与之前的名称不匹配
如何在R中修复:较长的对象长度不是较短的对象长度的倍数
如何在R中修复:对比度只能应用于有2个或更多层次的因素