I have a dataframe with values as below:
BrandName Expense
Apple $1.8B
Google $3.2B
GE -
facebook $281M
McDonald $719M
I want to clean these expense values such that they are finally on same scale (in billions). For ex the final data frame should look like:
BrandName Expense
Apple 1.8
Google 3.2
facebook 0.281
McDonald 0.719
$ can be simply removed by gsub. This is fine. But I am facing problem afterwards. I am applying a function A which uses grepl to check if the value contains 'M', if true (strip 'M', convert to numeric value, and divide by 1000) and if it returns false (strip 'B', convert to numeric value)
A <- function(x){
if (grepl("M", x))
{
str_replace(x, "M", "")
as.numeric(x)
x <- x/1000
}
else if (grepl("B", x))
{
str_replace(x, "B", "")
as.numeric(x)
}
}
frame <- data.frame(frame[1], apply(frame[2],2, A))
But all the expense values are coming out to be NA in final result. On further analysis, I noticed for all values, its going in elseif part. Am i making a bad use of grepl in apply function ? If yes how can i fix it.
or any other better solution to solve this particular problem?