Swinks95
Swinks95

Reputation: 21

Changing values into numeric values

I have a few columns where the value is for example : 525K or 1.1M. I want to convert those values to thousand or millions as numerics without using an extra R package besides baser and tidyr.

enter image description here

Is there anyone who can help me with a code or a function how I can do this in a simple and quick way?

I have tried to do it by hand with removing the 'M' or 'K' and the '.'.

players_set$Value <- gsub(pattern = "M", replacement = "000000 ", 
                           x = players_set$Value, fixed = TRUE)

Upvotes: 1

Views: 142

Answers (2)

akrun
akrun

Reputation: 887058

Here is another option with a named vector matching

getValue <- function(input) {
    # remove characters except LETTERS 
    v1 <- gsub("[0-9.€]+", "", input)
    # remove characters except digits
    v2 <- gsub("[A-Za-z€]+", "", input)
    # create a named vector
    keyval <- setNames(c(1e6, 1e3), c("M", "K"))
    # match the LETTERS (v1) with the keyval to get the numeric value
    # multiply with v2
    unname(as.numeric(v2) *keyval[v1])
}



getValue("525K")
#[1] 525000
getValue("1.1M")
#[1] 1100000

getValue("€525K")
#[1] 525000

getValue("€1.1M")
#[1] 1100000

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

For a base R option, we can try using sub to generate an arithmetic expression, based on the K or M unit. Then, use eval with parse to get the final number:

getValue <- function(input) {
    output <- sub("M", "*1000000", sub("K", "*1000", input))
    eval(parse(text=output))
}

getValue("525K")
getValue("1.1M")

[1] 525000
[1] 1100000

Upvotes: 2

Related Questions