Scaling up the intelligent concatenation of 2 columns in R
R is well-suited for vector operations.
It's not well-suited for loops,
which you should avoid as much as possible.

Consider this condition in your code:


if(is.na(data$Term_code[i]) &amp;&amp; !(is.na(data$Term_code1[i]))){
  data$Term_code[i] &lt;- data$Term_code1[i]
}



How about if we remove the second condition after the &amp;&amp;:


if(is.na(data$Term_code[i])){
  data$Term_code[i] &lt;- data$Term_code1[i]
}



The outcome won't change, right? If Term_code1 is not NA, then we'll get its value, if it's NA, well, we already had NA, so it makes no difference.

The good thing about this transformation is that now we can convert this directly to a vector operation without a loop:

no.term.code &lt;- is.na(data$Term_code)
data$Term_code[no.term.code] &lt;- data$Term_code1[no.term.code]


That is, set the values of Term_code to the values of Term_code1 where Term_code is NA.