Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round numbers in a tibble column with dplyr::mutate [duplicate]

Tags:

r

dplyr

I have the following tibble:

library(tidyverse)
tb <- structure(list(V2 = structure(c(2L, 1L, 4L, 3L, 2L, 1L, 4L, 3L
), .Label = c("bar", "foo", "gop", "qux"), class = "factor"), 
    V3m = c(9.394981, 6.826405, 1.074885, 1.493691, 1e-04, 2e-04, 
    3e-04, 4e-04)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-8L), .Names = c("V2", "V3m"))

Which looks like this:

> tb
# A tibble: 8 × 2
      V2      V3m
  <fctr>    <dbl>
1    foo 9.394981
2    bar 6.826405
3    qux 1.074885
4    gop 1.493691
5    foo 0.000100
6    bar 0.000200
7    qux 0.000300
8    gop 0.000400

How can I round V3m column to 2 digits? I tried this but failed:

tb %>% mutate(V3mR=format(V3m,2))
like image 757
neversaint Avatar asked Oct 21 '25 19:10

neversaint


1 Answers

We can use sprintf

tb %>% 
   mutate(V3mr = sprintf("%0.2f", V3m))

Using a reproducible example (edited by @Eric Fail)

titanic_4
# A tibble: 6 x 1
#   perc_survived
#           <dbl>
#1      50.00000
#2     100.00000
#3      97.14286
#4      44.44444
#5     100.00000
#6      19.23077

titanic_4 <- titanic_4 %>% 
               mutate(perc_survived_6 = sprintf("%0.6f", perc_survived))
titanic_4
# A tibble: 6 x 2
#   perc_survived perc_survived_6
#           <dbl>           <chr>
#1      50.00000       50.000000
#2     100.00000      100.000000
#3      97.14286       97.142857
#4      44.44444       44.444444
#5     100.00000      100.000000
#6      19.23077       19.230769

data

titanic_4 <- tibble(perc_survived = c(50.000000,
          100.000000, 97.142857, 44.444444, 100.000000, 19.230769))
like image 129
akrun Avatar answered Oct 23 '25 09:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!