Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading