如何使用dplyr :: mutate对tibble列中的数字进行舍入

时间:2017-04-18 07:14:54

标签: r dplyr

我有以下几点:

<?php
  $json_string = '{
                   "id":"PAY-4L2624428H450980CLD23F4A",
                   "intent":"sale",
                   "state":"approved",
                   "cart":"74345738MA858411Y",
                   "payer":{
                      "payment_method":"paypal",
                      "status":"VERIFIED",
                      "payer_info":{
                         "email":"haj.mohamed-facilitator@pmgasia.com",
                         "first_name":"test",
                         "last_name":"facilitator",
                         "payer_id":"Z2ZSX2WM9ALD2",
                         "shipping_address":{
                            "recipient_name":"test facilitator"
                         },
                         "country_code":"SG"
                      }
                   }
                }';
  $infoArr = json_decode($json_string, true);

  //1.Now you can use foreach():

                    //or 2.you can directly get the value by array index like below;
 echo "email : ".$infoArr["payer"]["payer_info"]["email"]."<br>";
 echo "first_name : ".$infoArr["payer"]["payer_info"]["first_name"]."<br>";
 echo "last_name : ".$infoArr["payer"]["payer_info"]["last_name"]."<br>";

看起来像这样:

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"))

如何将> 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 列舍入为2位?我尝试了但失败了:

V3m

1 个答案:

答案 0 :(得分:2)

我们可以使用sprintf

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

使用可重现的示例(由@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

数据

titanic_4 <- tibble(perc_survived = c(50.000000,
          100.000000, 97.142857, 44.444444, 100.000000, 19.230769))