2

Let's say I have this vector:

x <- c(0, 9, 352, 0.0523, 0.00006234, -12345, -1)

And I would like to increase the right-most digit by 1 regardless of the sign (+/-) of the number, how should I do it?

This is my desired output.

x_out <- c(1, 10, 353, 0.0524, 0.00006235, -12346, -2)
benson23
  • 16,369
  • 9
  • 19
  • 38

1 Answers1

2

You can create a function to compute the number of decimals (taken from this answer), and then do:

x + ifelse(x >= 0, 1, -1)*10^(-sapply(x, dec))

#[1]      1.00000000     10.00000000    353.00000000      0.05240000
#[5]      0.00006235 -12346.00000000     -2.00000000

With

dec <- function(x) {
  if ((x %% 1) != 0) {
    nchar(strsplit(sub('0+$', '', as.character(x)), ".", fixed=TRUE)[[1]][[2]])
  } else {
    return(0)
  }
}
Maël
  • 45,206
  • 3
  • 29
  • 67
  • For 0.00006234, your function returns 0.00006244 instead of 0.00006235 on my side, but for other numbers they are all good – benson23 Sep 06 '22 at 13:57
  • Weird. I can't reproduce this error. – Maël Sep 06 '22 at 13:58
  • 4
    "Last digit" isn't super well-defined for non-integers due to [floating point precision issues](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal). Different systems will perform differently even in the `as.character` conversion. – Gregor Thomas Sep 06 '22 at 14:00
  • @Maël It works fine after removing one decimal zero, maybe it's the limitation of computer arithmetic on floating point number on my system pointed out by Gregor Thomas – benson23 Sep 06 '22 at 14:07
  • I was going to suggest either `biginteger` or `Rmprf` to address the floating point, but find they're not currently available for `R-4.2.1`, so can't test. – Chris Sep 06 '22 at 14:36