title: R-apply a function to each row of a matrix, with a changing argument?
body: <p>I have a function with two arguments. The first argument takes vector, and the second argument takes a scalar. I want to apply this function to each row of a matrix, but this function takes different second argument every time. I tried the following, it didn't work. I expected to calculate the p.value for each row and then divide the p.value by the row number. I expected the result to be a vector, but I got a matrix instead. This is a pseudo example, but it illustrates my purpose. </p>
  
  <pre><code>&gt; foo = matrix(rnorm(100),ncol=20)
  &gt; f = function (x,y) t.test(x[1:10],x[11:20])$p.value/y
  &gt; goo = 1:5
  &gt; apply(foo,1,f,y=goo)
            [,1]      [,2]      [,3]       [,4]       [,5]
  [1,] 0.9406881 0.6134117 0.5484542 0.11299535 0.20420786
  [2,] 0.4703440 0.3067059 0.2742271 0.05649767 0.10210393
  [3,] 0.3135627 0.2044706 0.1828181 0.03766512 0.06806929
  [4,] 0.2351720 0.1533529 0.1371135 0.02824884 0.05105196
  [5,] 0.1881376 0.1226823 0.1096908 0.02259907 0.04084157
  </code></pre>
  
  <p>The following for loop strategy produces the expected result, expect would be very slow for the real data.</p>
  
  <pre><code>&gt; res = numeric(5)
  &gt; for (i in 1:5){
      res[i]=f(foo[i,],i)
      }
  &gt; res
  [1] 0.94068810 0.30670585 0.18281807 0.02824884 0.04084157
  </code></pre>
  
  <p>Any suggestions would be appreciated!</p>