I was looking for the quite basic numeric function digit sum in R.
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:
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.
The formula of the sum of first n natural numbers is S=n(n+1)2 .
This should be better:
digitsum <- function(x) sum(floor(x / 10^(0:(nchar(x) - 1))) %% 10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With