Search code examples
rnumericcoercion

How to avoid coercion of numeric values to NA in R


I have a data frame column x of character mode and class. The element in the column are all numeric values. I'm trying to convert the column values from character to numeric, but when I type as.numeric(x) only the integer values remain numeric, all the non-integer values (i.e 3.14) are coerced in NA. Why? How can I convert it to a column of numeric values avoiding the coercion to NA?
This is the output of dput(PercentageCont):

c("50,9", "56,9", "64", "57", "61,4",......)

When I do as.numeric all the floating point values are coerced in NA.


Solution

  • The problem lies in the commas. Here is my solution:

    # convert comma to dot
    dot = gsub(",","\\.", c("50,9", "56,9", "64"))
    
    [1] "50.9" "56.9" "64"
    
    # transform string into numeric
    as.numeric(dot)
    
    [1] 50.9 56.9 64.0