title: How to select range of columns in a dataframe based on their name and not their indexes?
body: <p>In a pandas dataframe created like this:</p>
  
  <pre><code>import pandas as pd
  import numpy as np
  
  df = pd.DataFrame(np.random.randint(10, size=(6, 6)),
                    columns=['c' + str(i) for i in range(6)],
                    index=["r" + str(i) for i in range(6)])
  </code></pre>
  
  <p>which could look as follows:</p>
  
  <pre><code>    c0  c1  c2  c3  c4  c5
  r0   2   7   3   3   2   8
  r1   6   9   6   7   9   1
  r2   4   0   9   8   4   2
  r3   9   0   4   3   5   4
  r4   7   6   8   8   0   8
  r5   0   6   1   8   2   2
  </code></pre>
  
  <p>I can easily select certain rows and/or a range of columns using <code>.loc</code>:</p>
  
  <pre><code>print df.loc[['r1', 'r5'], 'c1':'c4']
  </code></pre>
  
  <p>That would return:</p>
  
  <pre><code>    c1  c2  c3  c4
  r1   9   6   7   9
  r5   6   1   8   2
  </code></pre>
  
  <p>So, particular rows/columns I can select in a list, a range of rows/columns using a colon.</p>
  
  <p>How would one do this in R? <a href="https://stackoverflow.com/questions/10085806/extracting-specific-columns-from-a-data-frame">Here</a> and <a href="https://stackoverflow.com/questions/5234117/how-to-drop-columns-by-name-in-a-data-frame">here</a> one always has to specify the desired range of columns by their index but one cannot - or at least I did not find it - access those by name. To give an example:</p>
  
  <pre><code>df &lt;- data.frame(c1=1:6, c2=2:7, c3=3:8, c4=4:9, c5=5:10, c6=6:11)
  rownames(df) &lt;- c('r1', 'r2', 'r3', 'r4', 'r5', 'r6')
  </code></pre>
  
  <p>The command</p>
  
  <pre><code>df[c('r1', 'r5'),'c1':'c4']
  </code></pre>
  
  <p>does not work and throws an error. The only thing that worked for me is</p>
  
  <pre><code>df[c('r1', 'r5'), 1:4]
  </code></pre>
  
  <p>which returns</p>
  
  <pre><code>   c1 c2 c3 c4
  r1  1  2  3  4
  r5  5  6  7  8
  </code></pre>
  
  <p>But how would I select the columns by their name and not by their index (which might be important when I drop certain columns throughout the analysis)? In this particular case I could of course use <code>grep</code> but how about columns that have arbitrary names?</p>
  
  <p>So I don't want to use </p>
  
  <pre><code>df[c('r1', 'r5'),c('c1','c2', 'c3', 'c4')]
  </code></pre>
  
  <p>but an actual slice.</p>
  
  <p>EDIT:</p>
  
  <p>A follow-up question can be found <a href="https://stackoverflow.com/questions/37715085/how-to-slice-a-dataframe-by-selecting-a-range-of-columns-and-rows-based-on-names">here</a>.</p>