如何在R中抑制警告(有例子)

689 阅读2分钟

你可以使用以下方法来抑制R语言中的警告。

方法1:抑制特定行的警告

suppressWarnings(one line of code)

方法2:在全局范围内抑制警告

suppressWarnings({

several lines of code
just a bunch of code
lots and lots of code

})

下面的例子说明了如何在实践中使用每种方法,下面的代码产生了两条警告信息:

#define character vector
x <- c('1', '2', '3', NA, '4', 'Hey')

#convert to numeric vector
x_numeric <- as.numeric(x)

#display numeric vector
print(x_numeric)

Warning message:
NAs introduced by coercion 
[1]  1  2  3 NA  4 NA

#define two vectors
a <- c(1, 2, 3, 4, 5)
b <- c(6, 7, 8, 9)

#add the two vectors
a + b

[1]  7  9 11 13 11
Warning message:
In a + b : longer object length is not a multiple of shorter object length

方法1:抑制特定行的警告

我们可以将suppressWarnings()函数包在as.numeric()函数的周围,只抑制代码中的第一个警告:

#define character vector
x <- c('1', '2', '3', NA, '4', 'Hey')

#convert to numeric vector
suppressWarnings(x_numeric <- as.numeric(x))

#display numeric vector
print(x_numeric)

[1]  1  2  3 NA  4 NA

#define two vectors
a <- c(1, 2, 3, 4, 5)
b <- c(6, 7, 8, 9)

#add the two vectors
a + b

[1]  7  9 11 13 11
Warning message:
In a + b : longer object length is not a multiple of shorter object length

注意,第一个警告信息不再出现,但第二个警告信息仍然出现。

方法2:全局性地抑制警告信息

我们可以用suppressWarnings({})函数包住整段代码,全局地抑制所有的警告:

suppressWarnings({

#define character vector
x <- c('1', '2', '3', NA, '4', 'Hey')

#convert to numeric vector
suppressWarnings(x_numeric <- as.numeric(x))

#display numeric vector
print(x_numeric)

[1]  1  2  3 NA  4 NA

#define two vectors
a <- c(1, 2, 3, 4, 5)
b <- c(6, 7, 8, 9)

#add the two vectors
a + b

[1]  7  9 11 13 11

})

注意,这次我们没有收到任何警告,因为我们把**suppressWarnings({})**函数包在整个代码块中。

其他资源

下面的教程解释了如何在R中执行其他常见任务:

如何避免R警告:达到getOption("max.print")
如何处理R警告:glm.fit:算法没有收敛
如何修复:runtimewarning:double_scalars中遇到的无效值