title: How can I repeat calculations of many single colums and store the output in a new data frame in R?
body: <p>I never used loops but now need to repeat one calculation multiple times and want to store the output in a new data frame.</p>
  
  <p>I found some code that seems to fit but is not working.
  Please find an example of very few columns</p>
  
  <pre class="lang-r prettyprint-override"><code>df&lt;-data.frame("running.nr" = 1:5,
                 "spec1"= c(4,7,2,90,15),
                 "spec2"= c(3,10,48,10,4),
                 "spec3"= c(3,10,49,30,3),
                 "spec4"= c(10,27,99,130,22),
                 "n.id"= c(9,25,99,100,20))
  </code></pre>
  
  <p>This is the calculation I need to repeat for more than 50 columns. The output should be stored in a new dataframe also containing the "running.nr" column from df</p>
  
  <pre class="lang-r prettyprint-override"><code>perc.comp1&lt;-(df[,"spec1"]*100)/df$n.id
  perc.comp2&lt;-(df[,"spec2"]*100)/df$n.id
  perc.comp3&lt;-(df[,"spec3"]*100)/df$n.id
  perc.comp4&lt;-(df[,"spec4"]*100)/df$n.id
  
  df.perc&lt;-data.frame(df$running.nr,
                      perc.comp1,
                      perc.comp2,
                      perc.comp3,
                      perc.comp4)
  </code></pre>
  
  <p>This is the non-working loop I tried to make this code above less repetitive:</p>
  
  <pre class="lang-r prettyprint-override"><code>for(col in names(df)[2:5]) {
    df[paste0(col, "_pct")] = df[x] *100/ df$n.id}
  </code></pre>
  
  <p>This is the error message I get: 
  "Error in <code>[.data.frame</code>(df, x) : object 'x' not found"
  However, I am also not confident if the for loop results completely in want I want. Thanks for your time and help!</p>