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)
CodePudding user response:
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)
}
}