Search code examples
rregexgsuboperation

Mathematical operation on captured number that comes after a certain character in R


I have a vector that has elements like this:

x <- c("3434/1233", "3434.332/232.2", "220.23/932.89", "908.11111/9")

I want to replace the numbers after slash with their value multiplied by 60.

So the resulting vector will be:

x.times.sixty <- c("3434/73980", "3434.332/13932", "220.23/55973.4", "908.11111/540")

How can I do this?

I have tried the following which does not work:

gsub(x = x, pattern = "/(.*)", replacement = as.numeric('\\1' * 60))

Also this one:

gsub(x = x, pattern = "/(.*)", replacement = '\\1 * 60')

Solution

  • We can do the multiplication using gsubfn. Capture the numbers including the decimals at the end of the string (([0-9.]+$)), convert it to numeric and multiply by 60

    library(gsubfn)
    gsubfn("([0-9.]+$)", ~ as.numeric(x)*60, x)
    #[1] "3434/73980"     "3434.332/13932" "220.23/55973.4" "908.11111/540" 
    

    Or to follow the conditions correctly

    gsubfn("\\/([0-9.]+$)", ~ paste0("/", as.numeric(x)*60), x)
    #[1] "3434/73980"     "3434.332/13932" "220.23/55973.4" "908.11111/540"