title: Rvest: scraping data when element is not present
body: <p>I am having a tough time extracting the value as some pages have missing tag: <strong>result-cats</strong></p>
  
  <p>I have already visited this question <a href="https://stackoverflow.com/questions/33250826/scraping-with-rvest-complete-with-nas-when-tag-is-not-present">here</a>, however I am still not able to scrape the data.</p>
  
  <p><strong>HTML</strong>:</p>
  
  <pre><code>&lt;div class="result "&gt;
      &lt;span class="result-txt"&gt;
  
          &lt;span class="result-name"&gt;
              &lt;a href="/some/value/"&gt;COMPANY_NAME&lt;/a&gt;
              &lt;a class="result-icons" href="/some/value/COMPANY_NAME_/"&gt;
                  &lt;span title="Info" class="sprite sprite-info"&gt;Info&lt;/span&gt;
                  &lt;span title="Phone" class="sprite sprite-phone"&gt;Phone&lt;/span&gt;
              &lt;/a&gt;
          &lt;/span&gt;
  
          &lt;em&gt;
              &lt;a href="/some/value/"&gt;LOCATION&lt;/a&gt;
              &lt;span&gt; ADDRESS &lt;/span&gt;
          &lt;/em&gt;
  
          &lt;span class="result-cats"&gt;
              &lt;a href="/some/value/" title="CAT1"&gt;CAT1&lt;/a&gt;
              &lt;a href="/some/value/" title="CAT2"&gt;CAT2&lt;/a&gt;
          &lt;/span&gt;
  
      &lt;/span&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I am trying the following code, however it gives me error as some pages do not have <strong>results-cats</strong> tag. Hence the data frame has mismatch of vector length</p>
  
  <p><strong>code</strong></p>
  
  <pre><code>library(rvest)
  library(XML)
  library(stringi)
  
  df &lt;- data.frame(CompanyName = NULL, CompanyLink = NULL, Address = NULL, cats = NULL)
  
  for(i in 1:100 ){
  
    print(paste("Page: ", i, sep = ""))
  
    url &lt;- "url.com"
    page &lt;- read_html(url)
  
    CompanyNameNode &lt;- html_nodes(page,'.result-name a:nth-child(1)')
    CompanyName &lt;- html_text(CompanyNameNode)
    CompanyLink &lt;- html_attr(CompanyNameNode, 'href')
  
    Address &lt;- html_text(html_nodes(page,'.result-txt em'))
    Address &lt;- gsub("[\r\n]", "", Address)
  
    cats &lt;- html_text(html_nodes(page,'.result-cats'))
    cats &lt;- stri_trim(cats)
    cats &lt;- gsub("[\r\n]", ", ", cats)
  
    df &lt;- rbind(df, data.frame(CompanyName = CompanyName, 
                               CompanyLink = CompanyLink, 
                               Address = Address, 
                               cats = cats))
  
  }
  </code></pre>
  
  <p><strong>UPDATE</strong>: Issue resolved using following code</p>
  
  <pre><code>pg &lt;- html_nodes(page,'.result-txt')
  cats &lt;- NULL
  
  for(j in 1:length(pg)){
    cats[j] &lt;- ifelse(length(html_text(html_nodes(pg[j],'.result-cats')))==0, 
                     NA, 
                     html_text(html_nodes(pg[j],'.result-cats')))
  }
  
  cats &lt;- stri_trim(cats)
  cats &lt;- gsub("[\r\n]", ", ", cats)
  </code></pre>