Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

I generally prefer to code R so that I don't get warnings, but I don't know how to avoid getting a warning when using as.numeric to convert a character vector.

For example:

x <- as.numeric(c("1", "2", "X"))

Will give me a warning because it introduced NAs by coercion. I want NAs introduced by coercion - is there a way to tell it "yes this is what I want to do". Or should I just live with the warning?

Or should I be using a different function for this task?

1 Answer

0 votes
by
edited by

You can use the suppressWarnings() function to suppress warnings for a particular function as follows:

suppressWarnings(as.numeric(c("1", "2", "X")))

[1]  1  2 NA

You can also suppress warnings in the global setting temporarily using the options function as follows:

options(warn = -1)

x <- as.numeric(c("1", "2", "X"))

x

options(warn = defaultW)

Output:

x <- as.numeric(c("1", "2", "X"))

> x

[1]  1  2 NA

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...