title: Sum column and add result to dataframe in R
body: <p>I currently have a dataframe in R that contains one variable with a unique identifier, and several variables of that contain simply binary responses (0 or 1).</p>
  
  <p>A simplified version of my dataframe with two example rows:</p>
  
  <pre><code>c.names &lt;- c("ID", "male", "female")
  df &lt;- c("ADH0004", 0, 1,
          "ADH0005", 1, 0)
  df &lt;- matrix(df, nrow = 2, byrow = T)
  df &lt;- as.data.frame(df)
  names(df) &lt;- c.names
  df
  </code></pre>
  
  <p>In my final dataframe I will have potentially several hundred variables, all binary. I want to find a way to:</p>
  
  <ol>
  <li>obtain the column sum for each variable, and</li>
  <li>assign the column sum (1.) to a new variable (with the total copied in to each row)</li>
  <li>repeat this over each variable, so that I have n variables, and the same number of new variables with the totals in.</li>
  </ol>
  
  <p>Returning to my simple dataframe example, my new dataframe would look like:</p>
  
  <pre><code>c.names &lt;- c("ID", "male", "female", "male_t", "female_t")
  df &lt;- c("ADH0004", 0, 1, 1, 1,
          "ADH0005", 1, 0, 1, 1)
  df &lt;- matrix(df, nrow = 2, byrow = T)
  df &lt;- as.data.frame(df)
  names(df) &lt;- c.names
  df
  </code></pre>
  
  <p>To do this for one variable at a time is easy (even for me). I would simply:</p>
  
  <pre><code>df$male_t &lt;- sum(df$male)
  </code></pre>
  
  <p>I could do this for each variable manually, but I expect I could end up with up to a hundred, so I want to loop over this. I don't mind using a for loop (rather than apply) if that's easier, because I have a relatively small number of loops to do, so ease of coding is more of a priority than absolute speed of the code. Nevertheless I've tried both apply and for approaches.</p>
  
  <p>for:</p>
  
  <pre><code>varlist &lt;- c("male", female")
  for (i in varlist) {
    df$i_t &lt;- df$i
  }
  </code></pre>
  
  <p>(I've tried here to emulate a for loop I saw in Stata, where the total variables are generated with `i'_t, but this doesn't seem to work in R.</p>
  
  <p>I've also tried apply:</p>
  
  <pre><code>apply(df[c("male", "female")], MARGIN = 2, sum)
  </code></pre>
  
  <p>This gets me closer to my desired outcome, but I don't know how to save the column sums in the dataframe as new columns, rather than simply outputted to the console as they are now.</p>
  
  <p>Any suggestions would be greatly appreciated, naturally I've looked extensively on both stackoverflow and the wider internet.
  Phil</p>