title: Why must I rerun the code for apply function to work?
body: <p>In my global environment, I have variables that have the following names:</p>
  
  <blockquote>
    <ol>
    <li>filtered_A</li>
    <li>unfiltered_A</li>
    <li>filtered_B</li>
    <li>unfiltered_B</li>
    </ol>
  </blockquote>
  
  <p>and so on...</p>
  
  <p>The variable filtered_A is a subset of unfiltered_A that is a dataframe of one column containing gene names. I am trying to add a new column in unfiltered_A with two strings: "Passed" or "notPassed". "Passed" are those genes that exist in filtered_A. So basically I am building kind of a match between the two dataframes and write "Passed" or "notPassed" if they don't match.</p>
  
  <p>I have wrote the following code:</p>
  
  <pre><code>```{r unfiltered}
  setwd("/home/alaa/Documents/Analysis/genes/WES/unfiltered")
  
  # list that contains sample names 
  vcfFiles &lt;- list.files(getwd(), recursive = T)
  
  for (i in vcfFiles) {
      print(i)
      assign(paste0("unfiltered_", i), read.table(i))
  }
  ```
  
  
  ```{r filtered}
  setwd("/home/alaa/Documents/Analysis/genes/WES/filtered")
  
  for (i in vcfFiles) {
      print(i)
      assign(paste0("filtered_", i), read.table(i))
  }
  ```
  
  ```{r matching}
  
  for (i in vcfFiles){
  
    y &lt;- grep(i, ls())
  
  
    filterd &lt;- get(ls()[y[1]])
    unfilterd &lt;- get(ls()[y[2]])
  
    name_filterd &lt;- ls()[y[1]]
    name_unfilterd &lt;- ls()[y[2]]
  
    assign(name_unfilterd, cbind(unfilterd, apply(unfilterd, 1, function(x) ifelse(any(x[1] == filterd), 'Passed','notPassed'))))
  
  }
  
  for (i in ls()){
    if (is.data.frame(get(i)) &amp;&amp; ncol(get(i)) == 2 &amp;&amp; grepl(pattern = "unfiltered_", x = i)) {
      print(i)
      j &lt;- get(i)
      colnames(j)[2] &lt;- "Situation"
      assign(i, j)
    }
  }
  #rm(i, j, filterd, unfilterd, name_filterd, name_unfilterd, y)
  ```
  </code></pre>
  
  <p>If I run this code, it will fail on the first time saying:</p>
  
  <pre><code>    Error in apply(unfilterd, 1, function(x) ifelse(any(x[1] == filterd),  : 
    dim(X) must have a positive length
  </code></pre>
  
  <p>I do understand that this is due to unfilterd being dimensionless. However, if I rerun this code, it works without any problem.</p>
  
  <p>Can someone explain me what is wrong please and why is it failing on the first attempt?</p>
  
  <p>In case you are wondering why I am working using the global environment and ls(), its because I have many dataframes to match.</p>
  
  <p>Thanks in advance.</p>