Skip to contents

Returns an integer matrix that preserves the rounded colSums and rowSums.

Usage

round_matrix(Y, digits = 0, MARGIN = 0)

Arguments

Y

A matrix.

digits

Decimal places to round to.

MARGIN

One of

  • 0 Preserves the rounded colSums and rowSums.

  • 1 Preserves the rounded rowSums independently of each other.

  • 2 Preserves the rounded colSums independently of each other.

Value

The rounded matrix.

Details

The function will throw a *warning* if the problem is infeasable. To be able to round the matrix in this fashion, the following things must be equal:

  • the sum of the differences between the row totals and the rounded row totals

  • the sum of the differences between the column totals and the rounded row totals

Examples

set.seed(6)
Y <- rnorm(3*5)*10 |> matrix(3,5) |> round(3)
X <- round_matrix(Y)
Y
#>           [,1]       [,2]        [,3]      [,4]      [,5]
#> [1,]  2.696060 17.2719552 -13.0920430 -10.48397  6.532067
#> [2,] -6.299854  0.2418764   7.3862193  17.27851 -3.685665
#> [3,]  8.686598  3.6802518   0.4487299 -11.78600 -5.995546
X
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    3   17  -13  -11    7
#> [2,]   -6    0    7   18   -4
#> [3,]    8    4    1  -12   -6
colSums(Y) |> round()
#> [1]  5 21 -5 -5 -3
colSums(X)
#> [1]  5 21 -5 -5 -3
rowSums(Y) |> round()
#> [1]  3 15 -5
rowSums(X)
#> [1]  3 15 -5