Add currency rating in R

Asked

Viewed 749 times

5

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

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

To work in the R without problems, but I need to prepare a spending report and my boss asked to appear in the format of currency, 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 a function of any package that already does that, or will I have to create a regular expression?

3 answers

7


A simple and concise solution using the package stringr:

# 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 boxes after the comma, simply use the argument nsmall = 2.

  • It was something like this I was looking for, soon I test and I reply

2

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

First I used two functions (right and left) along the lines of functions direita and esquerda excel.

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

Then use 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 = " ")

2

Using paste and format:

paste("R$", format(3454575678, decimal.mark = ",", big.mark = ".", nsmall = 2)) 
"R$ 3.454.575.678,00"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.