convert a textual dollar value to a regular numeric value in R

Viewed 53

I have a dollar value written as "$164.72k" or "$1.72m", I would like to convert them to the usual numeric values 164720 and 1072000 respectively. what is the easiest way to accomplish this task?

2 Answers

I think this should work

library(tidyverse)


exsample_data <- tibble(values = c("$164.72k","$1.72m"))
exsample_data %>% 
  mutate(millions=str_detect(values,"m"), #Get indicator variable if number is in millions
         thousands=str_detect(values,"k"),
         values=str_remove(values,"k|m"),
         values=str_remove(values,"\\$"), #Remove the k, m and dollar sign
         values=as.numeric(values), #Convert from character to numeric
         values=ifelse(millions==TRUE,values*1000000,values), #Multiply by approrate amount to make it regular number, depending on whether it had a k or m
         values=ifelse(thousands==TRUE,values*1000,values))  
  

You may also define a custom function

vec <- c('$174.25k', '$123.78', '$134.56m', '$7.89b', '$340')


#custom function
mikhail <- function(cur_vec){
  x <- as.numeric(gsub('^\\$(\\d+\\.*\\d*).*$', '\\1', cur_vec))
  y <- gsub('^\\$\\d+\\.*\\d*(.*)$', '\\1', cur_vec)
  abb <- c('', 'k', 'm', 'b')
  act <- c(1, 1000, 1000000, 1000000000)
  x * act[match(y, abb)]
}

mikhail(vec)
#> [1] 1.7425e+05 1.2378e+02 1.3456e+08 7.8900e+09 3.4000e+02

Created on 2021-06-04 by the reprex package (v2.0.0)

Related