Search code examples
rdplyrformatcalculated-columnssubtraction

How to subtract a number from column value and keep leading zeros in front


So I want to be able to subtract 2400 from every number that is >= 2400 to correct for 26 hours time. The df looks like this:

Time
2519.39
2412.49
2554.12
2043.56

As you can see, the time here is in 26 hours clock for some reason. What I want is to do:

df <- df %>%
  mutate('Amended Time' = ifelse(Time >= 2400, Time - 2400, Time)

If I run this code, it does get rid of anything more than a 24 hrs clock, but also removes the 00's in front of it. Resulting in the following df:

Time     Amended Time
2519.39  119.39
2412.49  12.49
1954.12  1954.12
2043.56  2043.56

Now how do I make sure that whenever there is 2400 subtracted from the number, it keeps the total amount of numbers in every cell? So that eg, 2519.39 becomes 0119.39? etc..

Thanks in advance!


Solution

  • Since your expected output has 4 digits before the decimal point and 2 digits after, you can use sprintf as follows

    df %>%
      mutate(`Amended Time` = sprintf("%07.2f", ifelse(Time >= 2400, Time - 2400, Time)))
    

    Output

    #     Time Amended Time
    # 1 2519.39      0119.39
    # 2 2412.49      0012.49
    # 3 2554.12      0154.12
    # 4 2043.56      2043.56
    

    Of course the variable Amended Time will be character, not numeric.