title: Using apply family functions when loop over arguments in a function in r
body: <p>How can I loop over arguments in a functions using one of the apply type function to make code faster in R? For example, I have created a function to compute the joint mutual information of three random variables</p>
  
  <pre><code>### Function to loop over: Joint Mutual Information I({x_1,x_2};y)
  library(infotheo)
  JMI &lt;-function(x1,x2,y){
        entropy(cbind(x1,x2),method="emp") + entropy(y, method="emp") - 
        entropy(cbind(x1,x2,y),method="emp")
     } 
  </code></pre>
  
  <p>Suppose I have two matricies (x1, x2)  and one vector y like:</p>
  
  <pre><code>#### randomly generate binary variables from a bernoulli distribution
  set.seed(12345)
  f1 &lt;- rbinom(n=300,size=1,prob=0.5)
  f2 &lt;- rbinom(n=300,size=1,prob=0.5)
  f3 &lt;- rbinom(n=300,size=1,prob=0.5)
  
  ## creat y using xor operation of the two feature: x1 XOR x2
  #  this mean that y is 1 if f1[i]!=f2[i] and 0 otherwise
  y &lt;- ifelse(f1==f2,0,1)
  x1 &lt;-cbind(f1,f2)
  x2 &lt;- cbind(x1,f3)
  </code></pre>
  
  <p>Now, I want to loop over x1 and x2 in the JMI function. Using for-loops this looks like this:</p>
  
  <pre><code># a length(x1) x length(x2)-Matrix with zeros
  jmi &lt;- matrix(rep(0,ncol(x2)*ncol(x1)),
            nrow=ncol(x1),ncol=ncol(x2))
  #### For loops to be avoided
  for(i in 1:ncol(x1)){
    for(j in 1:ncol(x2)){
      jmi[i,j] &lt;- JMI(x1[,i],x2[,j],y)
    }#end out for(j)
  }#end inner for(i)
  </code></pre>
  
  <p>Is there an easy way to avoid both for-loops?</p>