-3

I have to total count of row and column total of a table. in the example it is 31, 92, 59 and 64. Also each cell can get the value maximum (Ex: max 20 for cell 1 and so on) of that indicated in the example.

Example :

enter image description here

How can I code it in R ? I tried with repeat loop , but no success !!

  • If anyone think the question need much research, needs clearly defined and easy , please comment or write. Negative vote will not make an idea about the merit of the question as well as of the voter !! – Mohammad Tanvir Ahamed Jun 29 '19 at 14:41
  • 2
    Edit your question as shown [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). I think the downvotes are due to adding your data as an image. – NelsonGon Jun 29 '19 at 15:25
  • Can you give an example of what one or two combinations would look like? It is not clear to me. – Jon Spring Jun 29 '19 at 16:36

1 Answers1

1

your table look like this:

a   b  | sab
c   d  | scd
----------
sac sbd| S

and you have 4 unknowns with 4 constraints (forget about the maximum constraints on a,b,c and d for a moment):

a+b=sab

a+c=sac

c+d=scd

b+d=sbd

the 4 constraints are not independent (otherwise you would have only one possible solution!), and a bit of algebra shows that the matrix of this linear system has rank 3. so you have one degree of freedom to play with. pick a for example, and then vary a from 0 to its maximum value. For each value of a then compute b, c and d using the row and column sum constraints, and check that they satisy the positivity and maximum constraints.

The R code for your example is as follows:

sab <- 59
scd <- 64
sac <- 31
sbd <- sab + scd - sac ### this is always true

amax <-  20
bmax <- 40
cmax <- 12
dmax <- 70

### let us vary a, our only degree of freedom
for (a in 0:amax){
    ### let us compute b, c and d by satisfying row and column sum constraints
    b <- sab - a
    c <- sac - a
    d <-  sbd - b
    ### let us check inequality constraints
    if (b <= bmax && b>= 0 && c <= cmax && c >= 0 && d <= dmax && d >= 0){
        cat("\nSolution:\n")
        print(m <- rbind(c(a,b),c(c,d)))
        cat("\nrowSums:", rowSums(m))
        cat("\ncolsums:", colSums(m))
        cat("\n---------------\n")
        if (! identical(rowSums(m), c(sab,scd)))
            stop("\nrow sum is not right!\n")
        if (! identical(colSums(m), c(sac,sbd)))
            stop("\ncolumns sum is not right!\n")
    }
}
FGirosi
  • 106
  • 5