1

I have a matrix of values and the sums of each row must equal 0 but at the moment they are close but not exactly zero (e.g. -3.12...e-15). I'd like to force the values in the rows to make a sum of 0.

EDIT:

I have a matrix where the diagonal must equal the negative sum of the row so that the rowSums() should be exactly 0.

For example:

A<-matrix(rexp(16, rate=.1), ncol=4)
diag(A)-rowSums(A)
   [1] -12.071549 -14.267157  -7.328108 -25.077841

diag(A)<-diag(A)-rowSums(A) #To make diagonal = negative sum

So rowSums(A) should be exactly 0 but they're not:

> rowSums(A)
[1]  0.000000e+00 -1.776357e-15 -8.881784e-16 -1.776357e-15
HCAI
  • 2,213
  • 8
  • 33
  • 65
  • 4
    Might be a machine precision issue. – jay.sf Sep 30 '20 at 12:24
  • 1
    Maybe you could use base functions such as `round()`, `trunc()` or `signif()` to get "true" 0s. Like `round(rowsum())` – Paul Sep 30 '20 at 12:26
  • @Paul signif() might be possible but I still need to make sure the rows sum to 0 so ideally I need to perform an operation on each element to ensure that. At the moment sum(signif(a[1,],6))=-4.48e-7 whereas sum(signif(a[1,],16))=-2.686653e-16 – HCAI Sep 30 '20 at 12:30
  • Seems strange to change the values in your matrix, is it possible to access the rowsum result and round it before it enters your functions that throw the error? – Paul Sep 30 '20 at 12:37
  • @Paul I agree, it's not ideal. But if you did want to deal with the matrix, what would you do? The problem is that I can't identify which operation is causing the problem when we generate the matrix in the first place. – HCAI Sep 30 '20 at 13:36
  • 1
    @Paul I've added a working example that illustrates what's going on. – HCAI Oct 01 '20 at 07:48
  • Could it be linked to the "floating point error"? I am not familiar with this but here are some SO threads: [Why are these numbers not equal?](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal); [How to deal with floating point errors in R](https://stackoverflow.com/questions/48886353/how-to-deal-with-floating-point-errors-in-r). I tried `> mapply(function(x) all.equal(0, x), rowSums(A)) [1] TRUE TRUE TRUE TRUE` – Paul Oct 01 '20 at 09:47
  • Maybe, the function you are using, has a `==` and should have a `all.equal()` instead as suggested by [this wiki](https://stackoverflow.com/a/9508558/10264278) – Paul Oct 01 '20 at 09:52

0 Answers0