-1

I am trying to add a new column by dividing column A and Column B using mutate() verb in R.

dataframe %>%
    mutate(colC = colA / colB)

But the new value in Column C is automatically getting rounded off to two decimal places. How do I avoid that from happening?

Manually dividing the value in the console is giving proper output up to ten decimal places.

ColA ColB ColC
6283 4835 1.30
5784 4567 1.27

In normal console: 6283 / 4835 --> 1.2994829369183040768

5784 / 4567 --> 1.2664768994963870874

user438383
  • 5,716
  • 8
  • 28
  • 43
DevrajR
  • 1
  • 1
  • 2
    Please show what command you are actually running. Also, the output is just being truncated, the same level of precision is still being used in the calculation. – user438383 Jan 07 '22 at 14:52
  • I am using a normal mutate() syntax. dataframe %>% mutate(colC = colA / colB) – DevrajR Jan 07 '22 at 14:56
  • This is just the rendering in your console for `tibbles`, the dataframe format in the tidyverse. If you use ColC again, it will use the un-rounded values. – Maël Jan 07 '22 at 14:59

1 Answers1

0

Let's see what is actually happening.

dplyr_res = df %>% mutate(ColC = ColA / ColB) %>% pull(ColC) %>% .[1]
  ColA ColB     ColC
1 6283 4835 1.299483
2 5784 4567 1.266477
base_res = 6283 / 4835
> identical(base_res, dplyr_res)
[1] TRUE

They are identical, the output is just truncated.

user438383
  • 5,716
  • 8
  • 28
  • 43
  • Got it. I actually saved the output in the new dataframe and on looking at view(dataframe) shows entire decimal values. – DevrajR Jan 07 '22 at 15:07
  • [What should I do if someone answers my question](https://stackoverflow.com/help/someone-answers). – user438383 Jan 07 '22 at 15:11