3

I have a 1000 x 3 matrix of combinations of the integers from 1:10 (e.g. each column is an index ranging from 1 to 10 and I want to look at combinations of indices). I would like to get the row index of the combination that results in a partial row sum satisfying some condition.

cvec = c(14,15)
L   <- 3
vec <- seq(10)
lst <- lapply(numeric(L), function(x) vec)
mat = as.matrix(expand.grid(lst))

partial = NULL
for (k in seq(L-1)){
  for (r in seq(L-k+1)){
    partial = c(which(rowSums(mat[,r:(r+k-1)])<=cvec[k]),partial)
  }
}

I keep getting the following error:

 Error in rowSums(mat[, r:(r + k - 1)]) : 
  'x' must be an array of at least two dimensions 

However, when I run which(rowSums(mat[,r:(r+k-1)])<=cvec[k]) or even just rowSums(mat[,r:(r+k-1)]) outside the for loops, I don't get an error. is there a reason for this?

stats134711
  • 624
  • 1
  • 5
  • 15
  • First off in the loop `partial` should be `partial[r,k]` otherwise it will be overwritten by the last iteration of the loop. You are likely getting the error because some version of `mat[, r:(r + k - 1)]` gives 1 column. – CCurtis Oct 25 '16 at 18:26
  • Thank you. What is an alternative to using rowSums? In the cases where `k=1`, then I have 1 column. However, this is still useful for me. Is there a work around? – stats134711 Oct 25 '16 at 18:42
  • 2
    try `rowSums(mat[,r:(r+k-1),drop=FALSE]` (ugh ...) – Ben Bolker Oct 25 '16 at 18:50
  • I would think so. Try omitting k=1 from the loop to see if that is really the problem. If so you can just run k=1 separately. – CCurtis Oct 25 '16 at 18:50
  • Thank you both! Adding the `drop=FALSE` option did the trick. – stats134711 Oct 25 '16 at 19:12

0 Answers0