-1

I am trying to convert a factor vector into numeric value without any changes in the value.

I looked up and found out some functions like

         bonds1 <- as.numeric(as.character(bonds$price)) 
         Warning message:
         NAs introduced by coercion 

         bonds1 <- as.numeric(levels(bonds$price)[bonds$price])
         Warning message:
         NAs introduced by coercion  

but as it is shown above, warning signs keep coming up. Any ideas on why this is not working?

[figured it out]

It was the commas in bonds$price

         bonds$price <- as.numeric(gsub(",","",bonds$price))
hk824
  • 21
  • 6

2 Answers2

2

You can remove the comma with gsub():

as.numeric(gsub(",","",as.character(factor(c("1,000.23","2.2", "one")))))
[1] 1000.23    2.20      NA
Warning message:
NAs introduced by coercion 
HubertL
  • 19,246
  • 3
  • 32
  • 51
-1

Like @HurbtL has mentioned it seems values are not convertible.

Check these SO answers on how to avoid this warning

Parse numerics with commas:

how to avoid "Warning message: NAs introduced by coercion" in as.numeric()

N1 <- c("1000", "1,000", "10000", "10,000")
as.numeric(N1)
##
[1]  1000    NA 10000    NA
Warning message:
NAs introduced by coercion
##
> N2 <- gsub(",","",N1)
> as.numeric(N2)
[1]  1000  1000 10000 10000

Supress warning

How to avoid warning when introducing NAs by coercion

Community
  • 1
  • 1
Deshan
  • 2,112
  • 25
  • 29