Home > Mobile >  Sum all integers > 9 individually in R. E.g. 10 = 1 0, 11 = 1 1
Sum all integers > 9 individually in R. E.g. 10 = 1 0, 11 = 1 1

Time:10-22

Im trying to write a function based on the Luhn algorithm (mod 10 algorithm), and I need a function that sums all integers > 9 in my number vector individually. E.g. 10 should sum to 1 0=1, and 19 should sum to 1 9=10. Example code:

nmr <- ("1_9_8_2_0_5_0_1_3_3_4_8")
nmr <- strsplit(nmr, "_")
nmr <- as.numeric(as.character(unlist(nmr[[1]])))
luhn_alg <- c(0,0,2,1,2,1,2,1,2,1,2,0)
x <- nmr*luhn_alg
x
[1]  0  0 16  2  0  5  0  1  6  3  8  0

sum(x)

[1] 41

I dont want the sum of x to equal 41. Instead I want the sum to equal: 0 0 1 6 2 0 5 0 1 6 3 8 0=32. I tried with a for loop but doesn't seem to get it right. Any help is much appreciated.

CodePudding user response:

You may need to split the data again after multiplying it with luhn_alg.

Luhn_sum <- function(x, y) {
  nmr <- as.numeric(unlist(strsplit(x, "_")))
  x1 <- nmr*y
  x1 <- as.numeric(unlist(strsplit(as.character(x1), '')))
  sum(x1)
}

nmr <- ("1_9_8_2_0_5_0_1_3_3_4_8")
luhn_alg <- c(0,0,2,1,2,1,2,1,2,1,2,0)
Luhn_sum(nmr, luhn_alg)
#[1] 32

CodePudding user response:

You can use substring and seq to create a vector of single digit numbers, then you only need to do a sum over them:

sum(
  as.numeric(
    substring(
      paste(x, collapse = ""), 
      seq(1, sum(nchar(x)), 1), 
      seq(1, sum(nchar(x)), 1)
    )
  )
)
  • Related