Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Digit sum function in R

Tags:

r

I was looking for the quite basic numeric function digit sum in R.

  • I did not find a preinstalled function.
  • Even in Stackoverflow's extensive R library I did not find a record.

Therefore tried myself ending with following function:

# Function to calculate a digit sum
digitsum = function (x) {sum(as.numeric(unlist(strsplit(as.character(x), split="")))) }

I works, but I still struggle with following two questions:

  1. Is there really in plain R no function for digit sum?
  2. Is there a smarter way to code this function?
like image 986
user2030503 Avatar asked Sep 07 '13 16:09

user2030503


People also ask

How do you calculate sum in R?

Sum function in R – sum(), is used to calculate the sum of vector elements. sum of a particular column of a dataframe. sum of a group can also calculated using sum() function in R by providing it inside the aggregate function.

How do you find the sum of N digits?

The formula of the sum of first n natural numbers is S=n(n+1)2 .


1 Answers

This should be better:

digitsum <- function(x) sum(floor(x / 10^(0:(nchar(x) - 1))) %% 10)
like image 51
Julius Vainora Avatar answered Sep 30 '22 15:09

Julius Vainora