title: Manipulating sub matrices in R
body: <pre><code>Nh&lt;-matrix(c(17,26,30,17,23, 17 ,24, 23), nrow=2, ncol=4); Nh
  Sh&lt;-matrix(c(8.290133, 6.241174, 6.096808, 7.4449672, 6.894924, 7.692115, 
               4.540521, 7.409122), nrow=2, ncol=4); Sh
  NhSh&lt;-as.matrix(Nh*Sh); NhSh
  rh&lt;-c( 0.70710678, 0.40824829, 0.28867513, 0.22360680, 0.18257419, 
         0.15430335, 0.13363062, 0.11785113, 0.10540926, 0.09534626); rh
  
  pv &lt;- c()
  for (j in 1:2) {
    for (i in 1:4) {
  
      pv &lt;- rbind(pv, NhSh[j,i]*rh)
    }
  }
  pv
  
  row.names(pv) &lt;- rep(c(1:2), each = 4)
  lst&lt;-lapply(split(seq_len(nrow(pv)), as.numeric(row.names(pv))), function(i) 
  pv[i,])
  
  data&lt;-40
  nlargest &lt;- function(x, data) 
  {
    res &lt;- order(x)[seq_len(data)];
    pos &lt;- arrayInd(res, dim(x), useNames = TRUE);
    list(values = pv[res], position = pos)
  }
  out &lt;- lapply(lst, nlargest, data = 40)
  </code></pre>
  
  <p>In continuation of above code Is there any brief way of repeating the following steps for each out$’k’$position for k in 1:2? </p>
  
  <pre><code>s1&lt;-c(1,1,1,1); ch&lt;-c(5,7,10,5); C&lt;-150; a&lt;-out$'1'$position 
  for (j in a[40:1, "row"] ) 
  {
   s1[j] &lt;- s1[j]+1;
   cost1 &lt;- sum(ch*s1);
   if (cost1&gt;=C) break
  }
  s1; cost1
  #Output [1] 5 6 6 5  
  
  #       [1] 152
  </code></pre>
  
  <p>I have to get 2 values for 's' and 'cost' for out$k$position. I tried </p>
  
  <pre><code>mat = replicate (2,{x = matrix(data = rep(NA, 80), ncol = 2)}); mat
  for (k in 1:2)
  {
    mat[,,k]&lt;-out$'k'$position
  }
  mat
  </code></pre>
  
  <p><strong>Error</strong> in mat[, , k] &lt;- out$k$position :number of items to replace is not a multiple of replacement length</p>
  
  <pre><code>for (k in 1:2)
  {
  for (j in mat[,,k][40:1] ) {
    s[j] &lt;- s[j]+1  
    cost &lt;- sum(ch*s)
    if (cost&gt;=C) break
  
  }
  }
  s; cost
  </code></pre>
  
  <p><strong>Error</strong> : Error in s[j] &lt;- s[j] + 1 : NAs are not allowed in subscripted assignments</p>
  
  <p>Please anyone help in resolving these errors.</p>