I need to find the sum of digits of the numbers in a vector and I wrote this:
once1<- 10:19
sum<-0
for (i in 1:10){
while(once1[i] > 0) {
resto <- once1[i] %% 10
sum[i] <- sum[i] resto
once1[i] <- once1[i] %/% 10
}
i<-i 1
}
sum
But it only works for the first iteration and cannot see why. Thank you very much in advance!
CodePudding user response:
Here's an alternative:
> sapply(strsplit(as.character(once1), ""), function(x){sum(as.numeric(x))})
[1] 1 2 3 4 5 6 7 8 9 10