11

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?

mickkk
  • 1,172
  • 2
  • 17
  • 38

1 Answers1

18

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)

abichat
  • 2,317
  • 2
  • 21
  • 39
  • I see. It's pretty ok but could potentially be misleading in case of quick "on the fly" analysis. Is there a dplyr option to avoid it? – mickkk Feb 07 '18 at 16:29
  • Why do you have to stick with a tibble when you want the output that a data.frame gives you? It doesn't change the underlying data, so it must be about presentation. If that's the case, then there are some more involved packages for tables like kableExtra, which are applied to the kable() function from knitr. – Spencer Castro Feb 07 '18 at 16:49
  • @SpencerCastro As I said, it's useless in a script. Here it's just to show that the data don't change with `as_tibble()`. – abichat Feb 07 '18 at 16:51
  • The "issue" (if we call it an issue) is when using summarise for instance. I do not use as_tibble but I get a tibble back, as expected. Anyway, ok, I can use as.data.frame in case of need. – mickkk Feb 07 '18 at 17:12