title: How to prevent sprintf error in R code
body: <p>I have a data frame with several columns. Whenever a row value of column V2 is less than 20,  the character element on the same row in column V4 is to be replaced by a string "sp_NameOfTopElement_NameOfBottomElement"</p>
  
  <p>My code: </p>
  
  <pre><code>R10 &lt;- data$V4
  positionBefore &lt;- match(R10,R10)
  itemBefore &lt;- R10[c(NA, positionBefore)]
  
  R10 &lt;- rev(data$V4))
  positionAfter &lt;- match(R10, R10)-1
  itemAfter &lt;- rev(R10[c(NA, positionAfter)])
  
  cond &lt;- if data$V2 &lt; 20
  data$R10[cond] &lt;- sprintf("sp_%s-%s", itemBefore[cond], itemAfter[cond])
  </code></pre>
  
  <p>After running my code, I got the following error:</p>
  
  <pre><code>Error in sprintf("sp_%s-%s", itemBefore[cond], itemAfter[cond]) :
  arguments cannot be recycled to the same length
  </code></pre>
  
  <p>Checking my variables:</p>
  
  <pre><code>NROW(itemBefore[cond]) = 200
  NROW(itemAfter[cond]) = 199
  </code></pre>
  
  <p>Obviously, two tow variables are unequal and I need to guard against this error.</p>
  
  <p>my solution which did not work:</p>
  
  <pre><code>cond &lt;- data$V2 &lt; 20
  if (any(itemAfter[cond]==0)){
      data$R10[cond] &lt;- sprintf("sp_%s-%s", itemBefore[cond], "none")}
  }else {data$R10[cond] &lt;- sprintf("sp_%s-%s", itemBefore[cond], itemAfter[cond])}
  </code></pre>
  
  <p>How can I get my solution code to work? Thanks</p>
  
  <p>EDIT:</p>
  
  <p>head(raw data):</p>
  
  <pre><code>V1  V2 V3   V4
  str 50  str2    pass
  tre 13  stup1   plus
  tre 70  vry plus
  carq    60  rty plus
  sty 17  tuc pass
  </code></pre>
  
  <p>head(expected result): </p>
  
  <pre><code>V1  V2 V3   V4
  str 50  str2    pass
  tre 13  stup1   sp_str_tre
  tre 70  vry plus
  carq    60  rty plus
  sty 17  tuc sp_carq_?
  </code></pre>
  
  <p>My problem is the last row of the data, where there is no other row below that row, and hence we have a situation like: sty 17  tuc sp_carq_?. The "?" indicates no item below.</p>