title: R for loop or apply on data table columns
body: <p>Trying to do some operation on each column in a data frame. Not sure to use <code>apply</code> or <code>for</code> (not sure how to ignore the first column in <code>apply</code>).</p>
  
  <p><strong>Question 1:</strong> </p>
  
  <p>To simply print each name twice I figured out:</p>
  
  <p><code>for (i in names(dt)){if(str_length(i) &lt; 3) {print(i);print(i)}}</code></p>
  
  <p>The first column's name is the only one with a string length > 3 which is why I used that.</p>
  
  <p>I tried using:</p>
  
  <pre><code>for (i in dt$i){if(str_length(names(i)) &lt; 3) {print(i);print(i)}}
  for (i in dt$i){if(str_length(names(dt)) &lt; 3) {print(i);print(i)}}
  </code></pre>
  
  <p>To simply print each column twice, but it just created an empty value.</p>
  
  <p><strong>Question 2:</strong> </p>
  
  <p>What I'd actually to do instead of print twice; is order each column: <code>order(-i)</code>??</p>
  
  <p>Then create a subset: <code>head(i, n=500)</code>??</p>
  
  <p>Not sure if this is extra step or an extension of the above step. Then define that as a data.frame; <code>dt(i) &lt; data.frame(head(i, n=500))</code>??</p>
  
  <p>Then save that table: <code>write.csv(dt(i), "newfolder/i.csv", row.names = FALSE)</code> - I think that will just constantly overwrite one file called i.csv, not sure how I'd name the file based on i.</p>
  
  <p>Maybe <code>apply</code> is a better approach, I'm not sure. </p>
  
  <p>I simplest approach (such that i understand what's going on) would be  appreciated. I only have 40 columns, each with 50,000 rows, so it shouldn't be that slow. </p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Trying to be more clear I will add an example:</p>
  
  <pre><code>Name  Math Science PE
  David  90    70    25
  Tom    100   60    40
  John   30    40    100
  </code></pre>
  
  <p>I would want to end with 3 csv's with the first looking like:</p>
  
  <pre><code>Name Math
  Tom  100
  David 90
  </code></pre>
  
  <p>In the above case n=2 for head. Also the csv could have the other columns, but they are not required.</p>