How to transform a number with a comma in R?

4

I have a csv file, saved via Excel (using the ";" as a column separator). When I import it into R, the numbers that are in the 0.00 format are factored and comma.

Ex: "123,45"

When you do the conversion, it stays as text.

num <- gsub("," , "." , "123,45")

num="123.45"

When I convert them individually they see number.

num <- as.numeric(num)

num = 123.45

But when I do this in a vector, the numbers are rounded.

numeros <- gsub(",",".",numeros)
numeros <- as.numeric(numeros)

numbers = 123 457 ...

Even using a loop, the same thing happens.

for (i in 1:lenght(numeros)) {
    numeros[i] <- as.numeric(numeros[i]
}

numbers = 123 457 ...

I would like to know how numbers with commas in numbers in the pattern of R.

    
asked by anonymous 20.04.2018 / 22:04

2 answers

5

When reading the data from the csv file, use the dec argument to specify the decimal separator:

read.csv('dados.csv', dec = ",")
    
20.04.2018 / 22:18
5

I believe that what you want to resolve with sub and not gsub .

x <- c("123,45", "456,78", "0,001")
y <- sub(",", ".", x)
y
[1] "123.45" "456.78" "0.001"

as.numeric(y)
[1] 123.450 456.780   0.001

Note that since 0.001 has three decimal places, the print.numeric method is smart enough to also give the other elements of the vector to 3 decimals.

Regarding @Willian Vieira's suggestion to use the dec = "," argument when reading the file, of course this is desirable, but R has the read.csv2 function precisely to read .csv files that come from countries where decimals are separated by commas.
On page help("read.table") (or read.csv , it's the same page) you can read the following. Emphasis mine.

  

read.csv and read.csv2 are identical to read.table except for the   defaults. They are intended for reading 'comma separated value'   files ('.csv') or (read.csv2) the variant used in countries that use   the comma the decimal point and the semicolon as field separator .

This seems to be the case described in the question.

    
21.04.2018 / 05:32