Add currency notation in R

5

I have the following problem here at work: in a data frame I have a column of Gross Value on certain date:

2016-02-01   751434574
2016-03-01   748873781
2016-04-01   755528121

To work on R without problems, but I need to prepare an expense report and my boss asked for it to appear in the currency format, as below:

2016-02-01   R$ 751.434.574
2016-03-01   R$ 748.873.781
2016-04-01   R$ 755.528.121

Is there any package function that already does this, or will I have to create a regular expression?

    
asked by anonymous 30.06.2017 / 14:21

3 answers

6

A simple and concise solution using the stringr package:

# Bibliotecas necessárias
library(magrittr)
library(stringr)

# Formatação para Reais
format_real <- function(values, nsmall = 0) {
  values %>%
    as.numeric() %>%
    format(nsmall = nsmall, decimal.mark = ",", big.mark = ".") %>%
    str_trim() %>%
    str_c("R$ ", .)
}

# Entrada exemplo
tabela <- data.frame(
  data = c("2016-02-01", "2016-03-01", "2016-04-01"),
  valor = c(751434574, 2435, 3454575678))

# Aplicação da formatação
format_real(tabela$valor)
#> [1] "R$ 751.434.574"   "R$ 2.435"         "R$ 3.454.575.678"

If you want to add houses after the comma, simply use the argument nsmall = 2 .

    
30.06.2017 / 16:04
2

It may not be the most elegant (or with the help of some package), but you can do it in the arm

First I used two functions ( right and left ) in the form of direita and esquerda functions of Excel.

left <- function(string,char){
  substr(string, 1, char)
}
right <- function(string, char){
  substr(string, nchar(string)-(char-1), nchar(string))
}

Then you used these functions with the command paste

dados <- data.frame(data = c("2016-02-01", "2016-03-01", "2016-04-01"),
                    valor = c(751434574,748873781,755528121))
dados$valor2 <- paste(left(dados$valor, 6),
                      right(dados$valor, 3), sep = ".")
dados$valor2 <- paste(left(dados$valor2, 3), right(dados$valor2, 7),
                      sep = ".")
dados$valor2 <- paste("R$", dados$valor2, sep = " ")
    
30.06.2017 / 15:27
1

Using paste and format :

paste("R$", format(3454575678, decimal.mark = ",", big.mark = ".", nsmall = 2)) 
"R$ 3.454.575.678,00"
    
05.07.2017 / 01:25