Temporarily Remove Warning Messages in R (Example)
In this R tutorial you’ll learn how to suppress a warning message in the RStudio console.
The content of the page looks as follows:
Here’s the step-by-step process:
Creation of Example Data
We’ll use the following data as a basis for this R programming tutorial.
x <- c("1.1", "1,1", "2", "3") # Create example data x # Print example data # [1] "1.1" "1,1" "2" "3"
The previous output of the RStudio console shows that our exemplifying data is a vector containing four numbers as formatted as character strings.
We may want to convert these data from the character to the numeric class using the as.numeric function:
as.numeric(x) # Produce warning message # [1] 1.1 NA 2.0 3.0 # Warning message: # NAs introduced by coercion
As you can see, the previous R code has returned the warning message “NAs introduced by coercion” to the RStudio console.
This is because the second vector element contains a decimal comma instead of a decimal point.
However, let’s assume that we want to remove this warning message from the console…
Example: Temporarily Avoid Warning Messages Using suppressWarnings() Function
In this example, I’ll explain how to suppress warning messages temporarily for the execution of only one function.
For this task, we can apply the suppressWarnings command as shown below:
suppressWarnings(as.numeric(x)) # Suppress warning message # [1] 1.1 NA 2.0 3.0
The previous R code has returned the same output as before. However, this time no warning message was displayed.
Note that we have suppressed the warning message only for this single line of code. In case you want to get rid of warning globally, you may have a look at this tutorial.
Video, Further Resources & Summary
Do you need further information on the content of this tutorial? Then I recommend watching the following video on my YouTube channel. In the video, I’m explaining the content of this tutorial.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may read the other articles on this website:
- Suppress Warnings Globally in R
- Fixing Error & Warning Messages in R (Overview)
- R Programming Examples
To summarize: At this point you should know how to avoid warning messages in the RStudio console output in the R programming language. If you have additional questions, please let me know in the comments. Furthermore, don’t forget to subscribe to my email newsletter to receive regular updates on the newest tutorials.