Search code examples
rcurrency

Currency conversion in R


I am trying to convert currency values from factor to numeric. The format is €110.5M €565K I was able to get rid of € sign, M and K letters but I also need to make the conversion as to show 110.5M=110.500.000 and 565K=565.000. Is there a way that you can suggest?

value<-as.numeric(gsub("[€MK]", "", as.character(strength[1:18207,1])))

Data to be converted

€110.5M €565K
€77M    €405K
€118.5M €290K

Solution

  • An option is gsubfn

    library(gsubfn)
    out <- unname(sapply(gsubfn("M|K", list(M = "* 1e6", K = "* 1e3"), 
        sub("€", "", str1)), function(x) eval(parse(text = x))))
    out
    #[1] 110500000    565000  77000000    405000 118500000    290000
    
    scales::dollar_format(prefix = "", big.mark = ".")(out)
    #[1] "110.500.000" "565.000"     "77.000.000"  "405.000"   
    #[4] "118.500.000" "290.000"    
    

    data

    str1 <- c("€110.5M",  "€565K", "€77M", "€405K", "€118.5M", "€290K")