Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does as_tibble() round floats to the nearest integer?

Tags:

r

dplyr

tibble

When using as_tibble in dplyr 0.7.4 and R 3.4.1 I get the following outputs

mtcars %>% aggregate(disp ~ cyl, data=., mean) %>% as_tibble()

which outputs

# A tibble: 3 x 2
    cyl  disp
  <dbl> <dbl>
1  4.00   105
2  6.00   183
3  8.00   353

while

mtcars %>% aggregate(disp ~ cyl, data=., mean)

outputs

  cyl     disp
1   4 105.1364
2   6 183.3143
3   8 353.1000

Not really surprisingly, the following

mtcars %>% group_by(cyl) %>% summarise(disp=mean(disp))

gives again

# A tibble: 3 x 2
    cyl  disp
  <dbl> <dbl>
1  4.00   105
2  6.00   183
3  8.00   353

Why is this rounding happening and how can I avoid it?

like image 410
mickkk Avatar asked Feb 07 '18 15:02

mickkk


People also ask

How do you round to 2 decimal places in R?

You can use the following functions to round numbers in R: round(x, digits = 0): Rounds values to specified number of decimal places. signif(x, digits = 6): Rounds values to specified number of significant digits. ceiling(x): Rounds values up to nearest integer.

How do you round in Summarise in R?

To round the output of summary function in R, we can use digits argument while applying the summary function.


1 Answers

This is not a rounding, it's only a way for {tibble} to display data in a pretty way:

> mtcars %>% 
+   aggregate(disp ~ cyl, data=., mean) %>% 
+   as_tibble() %>% 
+   pull(disp)
[1] 105.1364 183.3143 353.1000

If you want to see more digits, you have to print a data.frame:

> mtcars %>% 
+   aggregate(disp ~ cyl, data=., mean) %>% 
+   as_tibble() %>% 
+   as.data.frame()
  cyl     disp
1   4 105.1364
2   6 183.3143
3   8 353.1000

(and yes, the two last lines are useless)

like image 140
abichat Avatar answered Oct 16 '22 11:10

abichat