Multiply recursiverly in r

2019-09-13 21:44发布

Having the following matrix and vector.

x<-matrix(c(1,4,7,
         2,5,8,
         3,6,9), nrow = 3)
w <- c(1,1,1)
res <- c()

What is the best way to multiply recursiverly till obtain a desire sum of the results as exemplified:

res[1]<-w %*%x[1,]
res[2]<-w %*%x[2,]
res[3]<-w %*%x[3,]
res[4]<-w %*%x[1,]
res[5]<-w %*%x[2,]

sum(res)>1000 #Multiply recursiverly till the sum of the results sum(res) goes further than 1000. 

2条回答
Lonely孤独者°
2楼-- · 2019-09-13 21:56

Here is how to do it recursively:

f <- function(x, w, res){
    if (sum(res)>1000)
        return(res)
    res <- c(res, x%*%w)
    f(x,w,res)
}

Call it with your pre-defined objects. That is:

f(x, w, res)

Which will give you:

# [1]  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6
# [62] 15 24  6 15 24  6 15 24
查看更多
狗以群分
3楼-- · 2019-09-13 21:56

If you always have data on the same format then something along the lines

res <- min(floor(1000 / cumsum(rowSums(x)))) * cumsum(rowSums(x)) + cumsum(rowSums(x))
min(res[res>1000])

will give the answer to you without having to loop. Could be wrapped in a function to handle another value than 1000.

At least as how I understand your question

查看更多
登录 后发表回答