Pedro Bragança
Pedro Bragança

Reputation: 23

How to convert Character to numeric with U$

I'm very new in R and I have elementary questions.

I have a tbl who contains as follows

 Date         Debt
<date>         <chr>
2001-12-01    1,000,000
2002-01-01    2,000,000
2002-02-01    3,000,000

Above, I have a piece of code that follows. I want to transform Character in numeric, but I want to add U$ before the numbers with decimals.

library(magrittr)
library(stringr)
library(tidyverse)
#format to U$

format_dollar <- function(values, nsmall = 2) {
  values %>%
    as.numeric() %>%
  format(nsmall = nsmall, decimal.mark = ",",big.mark = ".") %>%
    str_trim() %>%
    str_c("U$", .)
}

format_dollar(tbl) %>% print()

But everytime I have runned this piece of code, this is the output

[1] "U$NA" "R$NA" "U$NA"

I would appreciate if anyone could help me, please

Upvotes: 1

Views: 54

Answers (1)

akrun
akrun

Reputation: 887981

The , would make the column character. By applying as.numeric, it would convert all of them to NA. Instead, we can remove those with str_remove_all and convert to numeric (but appending $ as prefix will make it to character class)

library(dplyr)
library(stringr)
tbl %>%
   mutate(Debt = as.numeric(str_remove_all(Debt, ',')))

Upvotes: 3

Related Questions