Digit sum function in R

前端 未结 4 1522
盖世英雄少女心
盖世英雄少女心 2020-12-06 17:17

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 libra
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 17:51

    I'm not sure why you would think there would be an inbuilt function to do that. It not really a statistical operation. More of a number theory sort of procedure. (There are many examples that can be found with a search of the Rhelp Archives. I use Markmail for that purpose but there are other search engines like RSeek, GMane, and the Newcastle webpage. Your function would take a series of numbers and return a single number that was the digit sum of all of them. If that were the goal then it looks reasonably designed. I would have guessed that one would want the digit sums from each number:

    sapply( c(1,2,123), 
            function(x) sum( as.numeric(unlist(strsplit(as.character(x), split=""))) ))
    [1] 1 2 6
    

    There is a "digitizing" funciton digitsBase in pkg:GLDEX, and you could replace your as.numeric(unlist(split(as.character(x),""))) with that function:

    digitsBase(x, 10)
    

提交回复
热议问题