Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...