title: custom function with ifelse and two objects needs to read from correct column in a dynamic way R
body: <p>How can I make sure the data of both columns in an object (Data)
   look in the corresponding columns of another object (B_u) in a dynamic way via a custom function?</p>
  
  <p>See example below:</p>
  
  <pre><code># example data
  require(xts)
  set.seed(3)    
  A    &lt;- matrix(runif(18, max=9), ncol=2)
  Data &lt;- xts(A, Sys.Date()-9:1)
  names(Data) &lt;- c("C1", "C2")
  </code></pre>
  
  <p>This generates:</p>
  
  <pre><code>                 C1       C2
  2016-04-28 1.512374 5.678813
  2016-04-29 7.267648 4.608143
  2016-04-30 3.464481 4.545215
  2016-05-01 2.949609 4.806318
  2016-05-02 5.418906 5.015245
  2016-05-03 5.439546 7.811275
  2016-05-04 1.121701 7.467378
  2016-05-05 2.651408 1.003042
  2016-05-06 5.198489 6.333195
  </code></pre>
  
  <p>Of this data I make quantiles (bottom 20% en top 20%):    </p>
  
  <pre><code># make quantiles based on dataset
  B_q  &lt;- (apply(t(Data), 1, FUN=quantile, probs=c(0.2,0.8), na.rm=TRUE))
  B_l  &lt;- B_q[1,]
  B_u  &lt;- B_q[2,]
  </code></pre>
  
  <p>Which results in:</p>
  
  <p>For B_l</p>
  
  <pre><code>  C1       C2
  2.195794 4.582972 
  </code></pre>
  
  <p>and B_u</p>
  
  <pre><code>      C1       C2 
  5.427162 6.786868
  </code></pre>
  
  <p>Create the function:</p>
  
  <pre><code># function to test whether data is bigger than the quantile
  test_a &lt;- function(x,l,u)
  {
     for (i in 1:(nrow(x)))
     for (j in 1:(ncol(x)))
  
      b &lt;- ifelse(x &gt; u[j] , 1, 0)
  
    return(b)
  }
  </code></pre>
  
  <p>Problem / question starts here when the function is called</p>
  
  <pre><code># calling the function (dynamic)
  # How can i make sure the data of both columns in Data
  # look in the corresponding columns of B_u?
  
  result_wrong &lt;- test_a(Data, B_l, B_u)
  </code></pre>
  
  <p>results in:</p>
  
  <pre><code>           C1 C2
  2016-04-28  0  0
  2016-04-29  1  0
  2016-04-30  0  0
  2016-05-01  0  0
  2016-05-02  0  0
  2016-05-03  0  1
  2016-05-04  0  1
  2016-05-05  0  0
  2016-05-06  0  0
  </code></pre>
  
  <p>Of which C1 for 2016-05-03 gives an incorrect result as it should be one. One can see this from the next result when I call the column explicitly</p>
  
  <pre><code># calling the function with explicit columns)
  # If I explicit the column to look into, it works. 
  # However I have 100 columns of data so that won't work
  
  result_correct &lt;- test_a(Data[,1], B_l[1], B_u[1])
  
             C1
  2016-04-28  0
  2016-04-29  1
  2016-04-30  0
  2016-05-01  0
  2016-05-02  0
  2016-05-03  1
  2016-05-04  0
  2016-05-05  0
  2016-05-06  0
  </code></pre>
  
  <p>So how to make sure that in the function the correct column with corresponding column of the quantiles (in this case B_u) is used?</p>