Changing Million/Billion abbreviations into actual numbers? ie. 5.12M -> 5,120,000 [duplicate]
Solution 1:
You can try this
num <- c("1.23M", "15.69B", "123.999M")
num <- gsub('B', 'e9', num)
num <- gsub('M', 'e6', num)
format(as.numeric(num), scientific = FALSE, big.mark = ",")
"84,060,000" "30,120,000,000" "251,290,000"
Solution 2:
Try this:
income <- c("84.06M", "30.12B", "251.29M")
toInteger <- function(income){
amt <- as.numeric(gsub("[A-Z]", "", income))
multiplier <- substring(income, nchar(income))
multiplier <- dplyr::case_when(multiplier == "M" ~ 1e6,
multiplier == "B" ~ 1e9,
TRUE ~ 1) # you can add on other conditions for more suffixes
amt*multiplier
}
>toInteger(income)
[1] 8.4060e+07 3.0120e+10 2.5129e+08
Solution 3:
You can change all your columns like this:
test = c("30.13B","84.06M","84.06B","84.06M")
values = sapply(strsplit(test,c("B","M")),function(x) as.numeric(x))
amount = sapply(strsplit(test,""), function(x) x[length(x)])
values2 = sapply(1:length(amount),function(x) ifelse(amount[x] == "B",values[x]*1e9,values[x]*1e6))
just replace test with the dataframe column you want to change and value
for the dataframe name and the column you are changing