You can find a nice infographic explaining how to understand the credit card number here.

Credit card numbers include, as the last digit, a simple checksum calculated using the Luhn algorithm. In essence, we add up the digits of the card number in a certain way, and if the resulting sum divided by 10 is not an integer (i.e., the reminder of dividing by 10 is zero), then the number is invalid (the reverse is not true; a number divisible by 10 can still be invalid).

This can be easily computed in R, although I suspect that there might be an easier way:

checkLuhn <- function( ccnum ) {
# helper function
sumdigits <- function( x )
sapply( x, function( xx )
sum( as.numeric( unlist( strsplit( as.character( xx ), "" ))))
)
# split the digits
ccnum <- as.character( ccnum )
v <- as.numeric( unlist( strsplit( ccnum, "" ) ) )
v <- rev( v )
# indices of every second digit
i2 <- seq( 2, length( v ), by= 2 )
v[i2] <- v[i2] * 2
v[ v > 9 ] <- sumdigits( v[ v > 9 ] )
if( sum( v ) %% 10 == 0 ) return( TRUE )
else return( FALSE )
}

### Like this:

Like Loading...

*Related*