How to avoid warning when introducing NS by coercion

I usually prefer the R code to not get warnings, but I don't know how to avoid the warning when using as.numeric to convert a character vector.

For example:

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

Give me a warning because he injected NAs by force. I want NAs to be coercive - is there a way to say this "yes, this is what I want to do." Or should I just live with a warning?

Or should I use another function for this task?

+96
casting r parsing na
Feb 20 '13 at 16:31
source share
5 answers

Use suppressWarnings() :

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

This suppresses warnings.

+121
Feb 20 '13 at 16:38
source share
— -

suppressWarnings() has already been mentioned. An alternative is to manually convert the problematic characters to NA first. For your specific problem, taRifx::destring does just that. Thus, if you receive another, unexpected warning from your function, it will not be suppressed.

 > library(taRifx) > x <- as.numeric(c("1", "2", "X")) Warning message: NAs introduced by coercion > y <- destring(c("1", "2", "X")) > y [1] 1 2 NA > x [1] 1 2 NA 
+30
Feb 20 '13 at 16:42
source share

In general, suppressing warnings is not the best solution, since you can be warned when unexpected input is provided.
The solution below is a wrapper to support only NA in data type conversion. No package required.

 as.num = function(x, na.strings = "NA") { stopifnot(is.character(x)) na = x %in% na.strings x[na] = 0 x = as.numeric(x) x[na] = NA_real_ x } as.num(c("1", "2", "X"), na.strings="X") #[1] 1 2 NA 
+15
Mar 26 '16 at 19:12
source share

You can use the stringr library.

 library(tidyverse) #For piping library(stringr) #Note: it part of "tidyverse" c("1", "2", "X") %>% stringr::str_extract_all("\\(?[0-9,.]+\\)?") %>% as.numeric() 
0
Mar 26 '18 at 7:32
source share

I had the same problem with the data frame column that I wanted to use for the y axis of the ggplot2 scatterplot, but here is how I solved it:

as.numeric(as.factor(columnName))

You may also find this useful instead of using suppressWarnings()

0
Apr 7 '19 at 14:23
source share



All Articles