title: how to replace for loop with function in R
body: <p>I would like to replace the loops in the following code. </p>
  
  <pre><code>    Test&lt;-function(j){
        card&lt;-5
        #matrix s is to hold the results
        s &lt;- matrix(rep(0,j*card),nrow=j,ncol=card,byrow=TRUE)
  
         # Loop1
         for (k in 1:j)
         { 
          #A vector should be drawn from another matrix, 
          #for simplicity, I define a vector "sol" to be modified in Loop2
          sol&lt;-rep(1,card)
          #Given the vector "sol", select a vector position randomly 
          #for a given no. of times (i.e. steps), say 10.
          step&lt;-10
  
              # Loop2 - Modify value in sol  
              for (i in seq_len(step))
              {
               #Draw a position
               r&lt;-sample(seq_len(card),1)
               #Each position has specific probabilities for 
               #assignment of possible values, meaning p is related to
               #the position. 
               #For simplicity, just define the probabilities by random here.
               p&lt;-runif(3,0,1)   # just create p for each step
               p&lt;-p/sum(p)       #
               #Finally, draw a value for the selected position and
               #value of sol within this loop is kept changing.
               sol[r]&lt;-sample(1:3,1,prob=p)
               }
          # keep the result in matrix s.
          s[k,]&lt;-sol }
      return(s)}
  </code></pre>
  
  <p>Given an input vector</p>
  
  <pre><code>         [,1] [,2] [,3] [,4] [,5]
      [1,]    1    1    1    1    1
  </code></pre>
  
  <p>It is expected to output a matrix like this:</p>
  
  <pre><code>         [,1] [,2] [,3] [,4] [,5]
      [1,]    1    1    3    2    3
      [2,]    1    1    1    1    3
      [3,]    2    2    2    2    3
      [4,]    2    1    2    2    1
      [5,]    1    1    3    1    1
  </code></pre>
  
  <p>Each step in Loop2 depends on a probability vector, which is then used to change value in the sol. Then I tried to replace Loop2 with sapply as follows:</p>
  
  <pre><code>    sapply(seq_len(steps), function(x){ 
        r&lt;-runif(seq_len(card),1)
        sol[r]&lt;-sample(1:3,1,prob=p) #Try to modify value in sol
       })
      s[k,]&lt;-sol #Actually, no change in sol.
  </code></pre>
  
  <p>However, values in sol has no changed keeping all 1s, i.e. 1,1,1,1,1. </p>
  
  <p>How can Loop2 be replaced by other apply family or other functions?</p>
  
  <p>Thank you.</p>