title: r conditional standard deviation on 2 matrices
body: <p>I am trying to calculate the conditional standard deviation of a matrix B (for every column) based on the values of matrix A.</p>
  
  <pre><code>#conditional function
  foo&lt;-function(x,y)
  {
    out&lt;-sd(y[abs(x)==1])
    return(out)
  }
  
  #create the matrix
  A&lt;-matrix(data=c(1,-1,0,1,0,0,0,0,1,1),nrow=5,ncol=2)
  B&lt;-matrix(data=c(3,4,5,6,7,8,9,10,11,12),nrow=5,ncol=2)
  
  #run for the first column
  foo(A[,1],B[,1])
  
  #run for both columns
  apply(X=A, MARGIN=2, FUN=function(x,y) foo(x,y), y=B)
  </code></pre>
  
  <p>the correct answer is 1.53 and 0.707 which I get when i run directly the foo individually for every column.</p>
  
  <p>However, when i try to run both columns with apply I get this result 3.06 2.94.</p>
  
  <p>Any idea how to change the apply in order to make it work cause I have a large matrix of assets (in xts object). Currently, I am using a for loop but I am sure it can be done with a more efficient way.</p>
  
  <p>Thank you in advance,</p>
  
  <p>Nikos</p>