0
votes

Having the following matrix and vector:

a<-matrix(c(1,4,7,
        2,5,8,
        3,6,9), nrow = 3)
b <- c(1,1,1)

How do I sum recursiverly over each line of the matrix inside a funciton till obtain a desired result using last result to calculate next operation as shown:

b<-b+a[1,]
b<-b+a[2,]
b<-b+a[3,]
b<-b+a[1,]
b<-b+a[2,]

sum(b)>100 # Sum recursiverly till obtain this result sum(b)>100

This operation looks similar to this answer Multiply recursiverly in r. However it uses results from previews operations to calculate next ones.

1

1 Answers

1
votes

Here's a recursive function to do what you're after,

# Sample Data
a<-matrix(c(1,4,7,
        2,5,8,
        3,6,9), nrow = 3)
b <- c(1,1,1)

We create a function that references itself with a value that increments modulo the number of rows

recAdd <- function(b, a, start = 1, size = NROW(a)) {
  if(sum(b) > 100) return(b)
  return(recAdd(b + a[start,], a, start = start %% size + 1, size))
}

> recAdd(b,a)
[1] 30 38 46

EDIT: Alternatively, here's a way with no recursion at all, which is much faster on large ratios of target number to sum of the matrix (but is slower on data of this size). Basically we get to take advantage of Euclid

nonrecAdd <- function(b, a, target = 100) {
  Remaining <- target - sum(b)
  perloop <- sum(a)
  nloops <- Remaining %/% perloop
  Remaining <- Remaining %% perloop
  if(Remaining > 0) {
    cumulativeRowsums <- cumsum(rowSums(a))
    finalindex <- which((Remaining %/% cumulativeRowsums) == 0)[1]
    b + colSums(a) * nloops +  colSums(a[1:finalindex,,drop = FALSE])
  } else {
    b + colSums(a) * nloops
  }
}