Dear StackOverflow community, I am working right now on a way to convert a vector of currency data stored as a character into a numeric vector with the ability to transform the currency into another currency.
So imagine my vector is:
x <- c("$5M", "€10B", "CHF5K")
and I would like to transform it into billion USD, so the result should be (random currency rates considered):
x <- c(5,11000,0.4)
I developed a solution for this with the creation of two functions, my first function removes the thousands, billions and millions characters and transforms it:
convMK <- function(cats){
for(i in 1:length(cats)){
if(grepl("M",cats[i])==TRUE){
cats[i] <- gsub("M","",cats[i])
} else if(grepl("K",cats[i])==TRUE){
temp <- "0."
cats[i] <- gsub("K","",cats[i])
cats[i] <-paste0(temp,cats[i])
} else if(grepl("B",cats[i])==TRUE){
temp <- "00"
cats[i] <- gsub("B","",cats[i])
cats[i] <-paste0(cats[i],temp)
cats[i] <- gsub("\\.","",cats[i])
} else{}
}
return(cats)
}
The second one transforms it into a numeric considering the exchange rates:
convCurr2 <- function(cats) {
catsNum <- c(0)
for (i in 1:length(cats)) {
if (grepl("\\$", cats[i]) == TRUE) {
cats[i] <- gsub("\\$", "", cats[i])
catsNum[i] <- as.numeric(cats[i])
catsNum[i] <- catsNum[i] * exUSD
} else if (grepl("\\€", cats[i]) == TRUE) {
cats[i] <- gsub("\\€", "", cats[i])
catsNum[i] <- as.numeric(cats[i])
catsNum[i] <- catsNum[i] * exEUR
} else if (grepl("CA", cats[i]) == TRUE) {
cats[i] <- gsub("CA", "", cats[i])
catsNum[i] <- as.numeric(cats[i])
catsNum[i] <- catsNum[i] * exCA
} else if (grepl("\\£", cats[i]) == TRUE) {
cats[i] <- gsub("£", "", cats[i])
catsNum[i] <- as.numeric(cats[i])
catsNum[i] <- catsNum[i] * exGBP
} else if (grepl("\\CHF", cats[i]) == TRUE) {
cats[i] <- gsub("CHF", "", cats[i])
catsNum[i] <- as.numeric(cats[i])
catsNum[i] <- catsNum[i] * exCHF
}
}
return(catsNum)
}
And then I would run the functions in that order:
cats<-convMK(cats)
cats <- convCurr2(cats)
My question now is: Isn't there an easier, shorter way? Because this seems to be way too complex! Especially because I still haven't implemented a solution to the problem, that the function also should look up the correct exchange rate to a given date.
I am very curious for your answers, I only started learning R one week ago and as a marketing student I don't have that much coding experience (meaning: none). Thus, I am eager learning to write more elegant code:)