title: Subsetting dataframe in R based on specifc pattern of columns
body: <p>I am computing the r-squared for multiple pairs of columns in a data frame. I can do this by individually writing out the code for each pair but I wanted to automate this using apply or some other vectorized approach based on the pattern of columns I am choosing from the data frame.</p>
  
  <p>Sample data:</p>
  
  <pre><code>set.seed(1234)
  dat &lt;- data.frame(replicate(18,rnorm(10)))
  </code></pre>
  
  <p>To get the r-squared for column 1 v. 2:</p>
  
  <pre><code>fit &lt;- lm(dat[,1] ~ dat[,2])
  summary(fit)$r.squared
  </code></pre>
  
  <p>But I would like to do all of the following combinations: {1, 2}, {2, 3}, {3, 1}, {4, 5}, {5, 6}, {6, 4}... etc. through the 18th column.</p>
  
  <p>In other words, all combinations of three with a window moving over to the next set of three each time. This way I can just call the function once on the whole data frame and get all the r-squared values at once instead of repeating the code 18 times.</p>