A few days ago I looked at a table in a report, where numbers were presented together with some positive or negative delta, i.e. "42.42 (+0.42)", "20.12 (- 10.12)". I was about to refactor the code and this is what I saw:
df <- tibble::tribble(
~x, ~delta,
45.17, -4.14,
40, 8.76
)
df
# A tibble: 2 × 2
# x delta
# <dbl> <dbl>
# 1 45.2 -4.14
# 2 40 8.76
`%>%` <- magrittr::`%>%`
df %>%
dplyr::mutate(
y = paste0(x, " (+", delta, ")")
) %>%
dplyr::mutate(
y = gsub(x = y, pattern = "+-", replacement = "-")
)
# A tibble: 2 × 3
# x delta y
# <dbl> <dbl> <chr>
# 1 45.2 -4.14 45.17 (+-4.14)
# 2 40 8.76 40 (+8.76)
It took me several minutes to understand how this works: first, add "+ delta", but it may be that delta is a negative number, so in a second step replace the "+-" sign with the minus sign... For my brain, this was like: you want to eat something, and you don't go directly to the kitchen, but you first go in the garden, then you go in the kitchen...
And that point, I admit, I didn't know what's the better way to do it, but it was clear to me that adding something just to remove it later cannot be the way to go. A short internet search revealed this solution:
# https://stackoverflow.com/questions/50959522/r-adding-in-front-of-positive-characters
`%>%` <- magrittr::`%>%`
df %>%
dplyr::mutate(
x = sprintf(x,fmt = "%2.2f"),
delta = sprintf(delta, fmt = "%+2.2f")
) %>%
dplyr::mutate(
y = paste0(x, " (+", delta, ")")
)
# A tibble: 2 × 3
# x delta y
# <chr> <chr> <chr>
# 1 45.17 -4.14 45.17 (+-4.14)
# 2 40.00 +8.76 40.00 (++8.76)
The idea: format the numbers the way you need it, then just paste them. sprintf adds the sign before the numbers and the needed number of digits:
sprintf("%+2.2f", 4.0)
# [1] "+4.00"
sprintf("%+2.2f", -4.0)
# [1] "-4.00"
With that occasion I remembered that some months ago I was learning for a Python certificate, there was a whole chapter on sprintf, I got bored relatively quickly and didn't see much point in learning all that. I was like a colleague put it recently: I do not need to learn all that stuff, it's in the internet anyway.
I can't find a way to gently say that this is just wrong. Yes, you could find it with an internet search. But: you work much more efficient if you already know the answer. And you at least need to know what to search for. In the example above: I guess the code writer searched for 'how do I replace a substring'...
Now to my lazy me, who got bored when learning about the sprintf format specifiers: this is like learning and practicing how to draw a rectangle when the final purpose is to "draw a bicycle".
Make a promise. Show up. Do the work. Repeat.