Convert column from date frame of characters to numeric

5

When trying to convert the text values of the columns of a data.frame , created using Stringasfactor = FALSE , numeric, I got an abnormal result by coercion:

> str(ccredito$Restaurantes)
 chr [1:20] "49,74" "15,98" "59,4" "14" "57,42" "64,4" "15,4" "29,9" "28,22" "12" "63,25" ...
> colunanumerica <- as.numeric(ccredito$Restaurantes)
Warning message:
NAs introduced by coercion 
> colunanumerica
[1] NA NA NA 14 NA NA NA NA NA 12 NA NA  6 NA NA NA NA 20 35 NA

How to correct and / or avoid this incorrect coercion?

    
asked by anonymous 12.05.2016 / 21:30

2 answers

2

Conversion of as.numeric treats . as integer / decimal separator, not , . A simple solution is to perform the exchange before calling as.numeric :

colunanumerica <- as.numeric(sub(",", ".", ccredito$Restaurantes))
    
12.05.2016 / 21:42
1

R does not understand , as a decimal separator, so you first need to replace them with dots and then convert them to numeric.

This can be done like this:

s <- c("49,74", "15,98", "59,4")
library(stringr)
s <- str_replace_all(s, ",", ".")
as.numeric(s)

Usually this can be fixed right after reading the data, using the dec = "," argument in the read.table function.

    
12.05.2016 / 21:45