Convert Character Frame Data Column to Numeric

Asked

Viewed 3,321 times

7

When trying to convert the text values of a column data.frame, created using Stringasfactor = FALSE, in numerical terms, I obtained 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?

2 answers

4

The conversion of as.numeric treats the . as integer/decimal separator, and not ,. A simple solution is to make the exchange before the call to as.numeric:

colunanumerica <- as.numeric(sub(",", ".", ccredito$Restaurantes))

2

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

It 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 away in reading the data, using the argument dec = "," in function read.table.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.