The sum of the digits in the numerical matrix per row

The presence of such a matrix as:

        [,1] [,2] [,3] [,4] [,5] [,6]
   [1,]   11   14   17   20   23   26
   [2,]   12   15   18   21   24   27
   [3,]   13   16   19   22   25   28

I want to get only lines with the sum of digits for each line between 2 values.

Sum of digits for each line:

   [1] 30
   [2] 38
   [3] 42

therefore, if I want to get only strings where the sum of the digits is between 31and 40, then only the string 2with the value should be returned 38.

+4
source share
2 answers

We can do it

 i1 <-  apply(m1, 1, function(x) {
         v1 <- sum(unlist(lapply(strsplit(as.character(x), ""), as.numeric)))
         v1 > 31 & v1 < 40})

m1[i1, , drop = FALSE]
#   [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   12   15   18   21   24   27

Or

i1 <- sapply(strsplit(do.call(paste0, as.data.frame(m1)), ""), 
               function(x) sum(as.integer(x)))
m1[i1, , drop = FALSE]

Or we can do

f1 <-  Vectorize(function(x) sum(floor(x / 10^(0:(nchar(x) - 1))) %% 10))
i1 <-  rowSums(t(apply(m1, 1, f1))) %in% 31:40
m1[i1, , drop = FALSE]

data

m1 <- matrix(11:28, nrow = 3)
+3
source

You can do:

l <- strsplit(as.character(t(m)), "")
mx <- max(lengths(l))
res <- rowSums(matrix(as.numeric(unlist(lapply(l, 'length<-', mx))), 
              ncol = ncol(m)*mx, byrow = TRUE), na.rm = TRUE)
m[res>31 & res<42,]

#[1] 12 15 18 21 24 27
  • l - list of all digits in m
  • mxis the maximum length of a number in m, just in case the number of digits is not equal for all numbers inside m(for your case, this 2)

  • ( NA) , rowSums m

  • (.. res), .
0

Source: https://habr.com/ru/post/1678409/


All Articles