1

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!

Ric S
  • 9,073
  • 3
  • 25
  • 51
tivoo
  • 115
  • 1
  • 1
  • 9
  • Related/possible duplicate https://stackoverflow.com/questions/5812493/how-to-add-leading-zeros – Ronak Shah Jun 22 '20 at 13:39
  • Thanks, I found that one but it does not directly explain how to apply the answer to a column mutate using dplyr. I got errors using the guidance from those answers – tivoo Jun 22 '20 at 13:40
  • `sprintf("%07.2f", x %% 2400)` – Eyayaw Jun 22 '20 at 13:50

1 Answers1

2

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.

Ric S
  • 9,073
  • 3
  • 25
  • 51