Home > OS >  Add 1 to the first even digit in a srting
Add 1 to the first even digit in a srting

Time:06-19

I have a vector of numeric values in R

x <- c(4320, 5400, 6786)

For each of this values I want to get a new value, where I sum 1 to the first non 0 even digit (starting from the right). The resulting vector should be:

[1] 4330  5500  6787

I haven't made any progresses so far. For numbers with only four digits, as in the example, I guess this could be accomplished with stringr and ifelse statements, iterating through each digit. But I was looking for a more general solution.

CodePudding user response:

fun <- function(x){
    y <- max(which(as.numeric(x) %%2 == 0 &x!='0'))
    x[y]<- as.numeric(x[y])   1
    as.numeric(paste0(x, collapse=''))
}

 sapply(strsplit(as.character(x), ''), fun)
[1] 4330 5500 6787

CodePudding user response:

Try this function

fn <- function(x) {
    y <- x ; add <- 1
    while(x != 0){
        if(x %% 10 != 0 & x %% 2 == 0 ) {
            y <- y   add
            break
        }
        x <- floor(x/10)
        add <- add * 10
    }
    y
}
fn <- Vectorize(fn)
fn(x)

#> [1] 4330 5500 6787

CodePudding user response:

Using Recursion and only numerical operations:

fun <- function(x, ten_times = 0, rem=0 ){
  ifelse(floor(x/10) == x/10, Recall(x/10, ten_times   1, rem),
    ifelse(x%%2 == 1, Recall(x%/, ten_times 1, rem   (x%)*10^ten_times),
         (x 1)*10^ten_times   rem))
}

fun(x)
[1] 4330 5500 6787

Note that this will throw an error if the number is purely made up of non-even numbers. eg fun(1111) will throw an error.

  •  Tags:  
  • r
  • Related