Boa!
Se você quiser arredondar um número, creio que a melhor opção é a função round()
.
Exemplo:
x <- 1.18321312
round(x)
#> [1] 1
round(x, 1)
#> [1] 1.2
round(x, 2)
#> [1] 1.18
Created on 2020-07-31 by the reprex package (v0.3.0)
Considere também as funções ceiling()
e floor()
para arredondar para cima ou para baixo respectivamente, sem casas decimais.
Para formatar um número existem várias opções, mas uma que gosto é a função scales::number()
x <- 1050.18321312
scales::number(x, accuracy = 1, big.mark = ".", decimal.mark = ",")
#> [1] "1.050"
scales::number(x, accuracy = 0.1, big.mark = ".", decimal.mark = ",")
#> [1] "1.050,2"
scales::number(x, accuracy = 0.01, big.mark = ".", decimal.mark = ",")
#> [1] "1.050,18"
Created on 2020-07-31 by the reprex package (v0.3.0)
Essas funções podem ser usadas dentro de um dplyr::mutate()
, modificando a coluna desejada.
library(magrittr)
set.seed(1)
tibble::tibble(x = rnorm(5) * 1000) %>%
dplyr::mutate(x2 = scales::number(x, accuracy = 0.01, big.mark = ".", decimal.mark = ","))
#> # A tibble: 5 x 2
#> x x2
#> <dbl> <chr>
#> 1 -626. -626,45
#> 2 184. 183,64
#> 3 -836. -835,63
#> 4 1595. 1.595,28
#> 5 330. 329,51
Created on 2020-07-31 by the reprex package (v0.3.0)