title: Working in table - function to work with margin sums and individual values
body: <p>Here is my small dataset</p>
  
  <pre><code>set.seed(123)
  X1 &lt;- rep(1:3, each = 4)
  X2 &lt;- c(1:4, 1:4, 1:4)
  Y &lt;- rnorm (12, 4, 20)
  myd &lt;- data.frame(X1, X2, Y)
  
  # "unmelten" form of the dataframe 
  aggregate(Y ~ X1, myd, 'c')
    X1         Y.1         Y.2         Y.3         Y.4
  1  1  -7.2095129  -0.6035498  35.1741663   5.4101678
  2  2   6.5857547  38.3012997  13.2183241 -21.3012247
  3  3  -9.7370570  -4.9132394  28.4816359  11.1962765
  </code></pre>
  
  <p>The actual data matrix is bigger in dimension. I want to write a function that use the melten form the data to a math like this:</p>
  
  <pre><code> Example for X1, Y1.1 cell 
  
    (X1,Y.1) - sum(X1 row) - sum(Y.1 column) + grand total (= sum(Y))
      -7.2095129 - ( -7.2095129 - 0.6035498 + 35.1741663  + 5.4101678) - ( -7.2095129 + 6.5857547 -9.7370570) + sum ( all values in the able)
  </code></pre>
  
  <p>Other two example to make my point clear.  </p>
  
  <pre><code>For X2, Y1.1 cell
       (X2,Y.1) - sum(X2 row) - sum(Y.1 column) + grand total (= sum(Y))
  
  For X3, Y.3 cell  
       (X3,Y.3) - sum(X3 row) - sum(Y.3 column) + grand total (= sum(Y))
  </code></pre>
  
  <p>Similarly this will output a matrix of 3 x 4 size for each cell in the matrix.</p>
  
  <p>I was trying to write a function to do this, but could get any idea. help please </p>