Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1004353
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T08:07:16+00:00 2026-05-16T08:07:16+00:00

I have written the following function to calculate a check digit in R. verhoeffCheck

  • 0

I have written the following function to calculate a check digit in R.

verhoeffCheck <- function(x)
{
## calculates check digit based on Verhoeff algorithm
## note that due to the way strsplit works, to call for vector x, use sapply(x,verhoeffCheck)

## check for string since leading zeros with numbers will be lost
if (class(x)!="character"){stop("Must enter a string")}

#split and convert to numbers
digs <- strsplit(x,"")[[1]]
digs <- as.numeric(digs)

digs <- rev(digs)   ## right to left algorithm

## tables required for D_5 group

d5_mult <- matrix(c(
                 0:9,
                 c(1:4,0,6:9,5),
                 c(2:4,0:1,7:9,5:6),
                 c(3:4,0:2,8:9,5:7),
                 c(4,0:3,9,5:8),
                 c(5,9:6,0,4:1),
                 c(6:5,9:7,1:0,4:2),
                 c(7:5,9:8,2:0,4:3),
                 c(8:5,9,3:0,4),
                 9:0
                 ),10,10,byrow=T)

d5_perm <- matrix(c(
                 0:9,
                 c(1,5,7,6,2,8,3,0,9,4),
                 c(5,8,0,3,7,9,6,1,4,2),
                 c(8,9,1,6,0,4,3,5,2,7),
                 c(9,4,5,3,1,2,6,8,7,0),
                 c(4,2,8,6,5,7,3,9,0,1),
                 c(2,7,9,3,8,0,6,4,1,5),
                 c(7,0,4,6,9,1,3,2,5,8)
                 ),8,10,byrow=T)

d5_inv <- c(0,4:1,5:9)

## apply algoritm - note 1-based indexing in R
d <- 0

for (i in 1:length(digs)){
    d <- d5_mult[d+1,(d5_perm[(i%%8)+1,digs[i]+1])+1]
    }

d5_inv[d+1]
}

In order to run on a vector of strings, sapply must be used. This is in part because of the use of strsplit, which returns a list of vectors. This does impact on the performance even for only moderately sized inputs.

How could this function be vectorized?

I am also aware that some performance is lost in having to create the tables in each iteration. Would storing these in a new environment be a better solution?

  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T08:07:17+00:00Added an answer on May 16, 2026 at 8:07 am

    If your input strings can contain different numbers of characters, then I don’t see any way round lapply calls (or a plyr equivalent). The trick is to move them inside the function, so verhoeffCheck can accept vector inputs. This way you only need to create the matrices once.

    verhoeffCheckNew <- function(x)
    {
    ## calculates check digit based on Verhoeff algorithm
    
    ## check for string since leading zeros with numbers will be lost
      if (!is.character(x)) stop("Must enter a string")
    
      #split and convert to numbers
      digs <- strsplit(x, "")
      digs <- lapply(digs, function(x) rev(as.numeric(x)))
    
      ## tables required for D_5 group
      d5_mult <- matrix(c(
                       0:9,
                       c(1:4,0,6:9,5),
                       c(2:4,0:1,7:9,5:6),
                       c(3:4,0:2,8:9,5:7),
                       c(4,0:3,9,5:8),
                       c(5,9:6,0,4:1),
                       c(6:5,9:7,1:0,4:2),
                       c(7:5,9:8,2:0,4:3),
                       c(8:5,9,3:0,4),
                       9:0
                       ),10,10,byrow=T)
    
      d5_perm <- matrix(c(
                       0:9,
                       c(1,5,7,6,2,8,3,0,9,4),
                       c(5,8,0,3,7,9,6,1,4,2),
                       c(8,9,1,6,0,4,3,5,2,7),
                       c(9,4,5,3,1,2,6,8,7,0),
                       c(4,2,8,6,5,7,3,9,0,1),
                       c(2,7,9,3,8,0,6,4,1,5),
                       c(7,0,4,6,9,1,3,2,5,8)
                       ),8,10,byrow=T)
    
      d5_inv <- c(0,4:1,5:9)
    
      ## apply algorithm - note 1-based indexing in R      
      sapply(digs, function(x)
      {
        d <- 0  
        for (i in 1:length(x)){
            d <- d5_mult[d + 1, (d5_perm[(i %% 8) + 1, x[i] + 1]) + 1]
            }  
        d5_inv[d+1]
      })
    }
    

    Since d depends on what it was previously, the is no easy way to vectorise the for loop.

    My version runs in about half the time for 1e5 strings.

    rand_string <- function(n = 12) 
    {
      paste(sample(as.character(0:9), sample(n), replace = TRUE), collapse = "")
    }
    big_test <- replicate(1e5, rand_string())
    
    tic()
    res1 <- unname(sapply(big_test, verhoeffCheck))
    toc()
    
    tic()
    res2 <- verhoeffCheckNew(big_test)
    toc()
    
    identical(res1, res2) #hopefully TRUE!
    

    See this question for tic and toc.

    Further thoughts:

    You may want additional input checking for "" and other strings that return NA when converted in numeric.

    Since you are dealing exclusively with integers, you may get a slight performance benefit from using them rather than doubles. (Use as.integer rather than as.numeric and append L to the values in your matrices.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have written the following algorithm in order to evaluate a function in MatLab
I have written the following function but it's isn't returning anything when I run
I have written following function which checks whether start_date field is not empty and
I have written the following function which adds an event listener and registers the
I have written the following function: -- Gets stats for all markets CREATE OR
I have written the following function: it takes in a variable input_name ; The
I have written the following function meant to update a student in my database:
So I am working on Problem 31 . I have written the following function
If you look at http://www.danfarrellwright.com/screwsline/front_end/product.php?product_id=104 I have written the following function to add the
I have written the following code function byId(id) { return document.getElementById(id); } function addElm(root,elm)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.