You can use the following methods to suppress warnings in R:
Method 1: Suppress Warnings on Specific Line
suppressWarnings(one line of code)
Method 2: Suppress Warnings Globally
suppressWarnings({ several lines of code just a bunch of code lots and lots of code })
The following examples show how to use each method in practice with the following code, which produces two warning messages:
#define character vector x #convert to numeric vector x_numeric 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 #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
Method 1: Suppress Warnings on Specific Line
We can wrap the suppressWarnings() function around the as.numeric() function to suppress only the first warning in the code:
#define character vector x #convert to numeric vector suppressWarnings(x_numeric numeric(x)) #display numeric vector print(x_numeric) [1] 1 2 3 NA 4 NA #define two vectors a #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
Notice that the first warning message no longer appears but the second warning message still appears.
Method 2: Suppress Warnings Globally
We can wrap the suppressWarnings({}) function around the entire chunk of code to suppress all warnings globally:
suppressWarnings({ #define character vector x #convert to numeric vector suppressWarnings(x_numeric numeric(x)) #display numeric vector print(x_numeric) [1] 1 2 3 NA 4 NA #define two vectors a #add the two vectors a + b [1] 7 9 11 13 11 })
Notice that we don’t receive any warnings this time because we wrapped the suppressWarnings({}) function around the entire chunk of code.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Avoid R Warning: reached getOption(“max.print”)
How to Handle R Warning: glm.fit: algorithm did not converge
How to Fix: runtimewarning: invalid value encountered in double_scalars