title: looping over the name of the columns in R for creating new columns
body: <p>I am trying to use the loop over the column names of the existing dataframe and then create new columns based on one of the old column.Here is my sample data: </p>
  
  <pre><code> sample&lt;-list(c(10,12,17,7,9,10),c(NA,NA,NA,10,12,13),c(1,1,1,0,0,0))
      sample&lt;-as.data.frame(sample)
      colnames(sample)&lt;-c("x1","x2","D")
  
  &gt;sample
  x1  x2  D
  10  NA  1
  12  NA  1
  17  NA  1
  7   10  0
  9   20  0
  10  13  0
  </code></pre>
  
  <p>Now, I am trying to use <code>for loop</code> to generate two variables x1.imp and x2.imp that have values related to D=0 when D=1 and values related to D=1 when D=0(Here I actually don't need <code>for loop</code> but for my original dataset with large cols (variables), I really need the loop) based on the following condition:</p>
  
  <pre><code>for (i in names(sample[,1:2])){
  sample$i.imp&lt;-with (sample, ifelse (D==1, i[D==0],i[D==1]))
  i=i+1
  return(sample)
  }
  
  
  Error in i + 1 : non-numeric argument to binary operator
  </code></pre>
  
  <p>However, the following works, but it doesn't give the names of new cols as imp.x2 and imp.x3</p>
  
  <pre><code>for(i in sample[,1:2]){
  impt.i&lt;-with(sample,ifelse(D==1,i[D==0],i[D==1]))
  i=i+1
  print(as.data.frame(impt.i))
   }
  
  impt.i
  1      7
  2      9
  3     10
  4     10
  5     12
  6     17
    impt.i
  1     10
  2     12
  3     13
  4     NA
  5     NA
  6     NA
  </code></pre>
  
  <p>Note that I already know the solution without loop<a href="https://stackoverflow.com/questions/15439359/replace-the-values-using-iflelse-in-r"> [here]</a>. I want with loop.</p>
  
  <p>Expected output:</p>
  
  <pre><code>x1  x2  D   x1.impt x2.imp 
  10  NA  1   7       10      
  12  NA  1   9       20
  17  NA  1   10      13
  7   10  0   10      NA
  9   20  0   12      NA
  10  13  0   17      NA
  </code></pre>
  
  <p>I would greatly appreciate your valuable input in this regard. </p>