Search code examples
rvectorsumdigits

vectorised function to calculate sum of digits


I have a vector of numbers (eg. c(1, 11, 1232, 4221, 2)), and I need a corresponding vector of the sums of digit of each element (c(1, 2, 8, 9, 2), in the previous example).

I found some nice solutions for single numbers. the nicest (from Digit sum function in R) is:

digitsum <- function(x) sum(floor(x / 10^(0:(nchar(x) - 1))) %% 10)

However, this solution is not vectorized. It would only work on one element at a time.

And so, Is there a way to vectorize this solution, and create a similar function that would work on vectors? (instead of looping through all elements, that is)


Solution

  • > x=c(1, 11, 1232, 4221, 2)
    > sapply(strsplit(as.character(x),""),function(y){sum(as.numeric(y))})
    [1] 1 2 8 9 2