Comma to Numeric number conversion in R

Asked

Viewed 122 times

2

I have a script that receives a user value, via readLines. This value is a number (monetary value) with two decimal places that must be saved in a frame date.

However, when I convert the received value to Numeric, the R rounds to integer.

valor <- readLines("stdin", n = 1)
valor <- sub(",", ".", valor)#troca vírgula por ponto
valor <- as.numeric(as.character(valor))

I’ve also tried with type.convert, but the same behavior happens.

  • When you say "This value is a number (monetary value)", it means that the user enters a type value R$ 3,14 or he comes in with 3,14 straightforward?

  • is 3.14, that’s why I use sub to exchange the comma for a period. I saw that type.Converttem um parâmetroDec``` to indicate the decimal character, however it also rounds the result.

1 answer

3

In fact, the R is not rounding the value, it just doesn’t display all the decimal places as can be seen in this reply Convert Character to number without the Loss of decimal in R

Including the parameter digits in print, we see that decimal places are there. The same happens if we save the data frame to CSV.

So if we use valor <- type.convert(valor, dec = ",") and show with print(valor, digits = 15) decimal places are displayed correctly.

If we apply print(sum(df$valor), digits = 15)we will get the correct value displayed correctly.

Browser other questions tagged

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