I am trying to calculate the conditional standard deviation of a matrix B (for every column) based on the values of matrix A.
#conditional function
foo<-function(x,y)
{
out<-sd(y[abs(x)==1])
return(out)
}
#create the matrix
A<-matrix(data=c(1,-1,0,1,0,0,0,0,1,1),nrow=5,ncol=2)
B<-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)
the correct answer is 1.53 and 0.707 which I get when i run directly the foo individually for every column.
However, when i try to run both columns with apply I get this result 3.06 2.94.
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.
Thank you in advance,
Nikos