1

Apologies if this has been dealt with before, I'm somewhat of a noob and can't seem to see anything similar.

I want to run a function on a matrix of data, but I want to run the function multiple times, each time with a different row of my matrix removed i.e. first with row 1 removed, then with row 2 removed (but with row 1 present), then with row 3 removed (but with row 1 and row 2 present) etc.

Example

Lets say I have a matrix with ten rows and ten columns:

matrix <- matrix(1:100, nrow=10, ncol=10)
row.names(matrix) <- c(1:10)

    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
1     1   11   21   31   41   51   61   71   81    91
2     2   12   22   32   42   52   62   72   82    92
3     3   13   23   33   43   53   63   73   83    93
4     4   14   24   34   44   54   64   74   84    94
5     5   15   25   35   45   55   65   75   85    95
6     6   16   26   36   46   56   66   76   86    96
7     7   17   27   37   47   57   67   77   87    97
8     8   18   28   38   48   58   68   78   88    98
9     9   19   29   39   49   59   69   79   89    99
10   10   20   30   40   50   60   70   80   90   100

And lets say I want to take the sum of the matrix 10 times, each time with a different row removed.

I can do this manually via:

sum(matrix[-1,])
sum(matrix[-2,])
sum(matrix[-3,])
sum(matrix[-4,])
etc

But this is slow (my actual matrix has nearly 10,000 rows).

I'm trying to write a for loop to do this in one go, but after a couple of hours of banging my head against a brick wall, I'm getting nowhere.

Has anyone solved this before?

1 Answer 1

0

We can do this with sapply to loop through the sequence of rows, then get the sum of the 'matrix' after removing the row index

sapply(seq_len(nrow(matrix)), function(i) sum(matrix[-i,]))
#[1] 4590 4580 4570 4560 4550 4540 4530 4520 4510 4500

Or we can do this in a vectorized way by subtracting the sum of 'matrix' with the rowSums of 'matrix'

unname(sum(matrix) - rowSums(matrix))
#[1] 4590 4580 4570 4560 4550 4540 4530 4520 4510 4500
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.