title: R: subset a data frame with a vector that tells from what column to take values
body: <p>I have a data frame with 3 columns and a vector with values ranging between 1 and 3 (# of columns in my data frame) and the same length L as the number of rows in the data frame.</p>
  
  <p>I need to produce a vector of values (also with length L) from the data frame so that for the Nth row the value is taken from the data frame column that is indicated by the Nth element the vector. Below is an example.</p>
  
  <p>I'd like to have it done without loops but using indexing - because I need this operation to be very fast and my actual data frame is very large.</p>
  
  <pre><code>vec &lt;- c(1:3, 1:3)
  df &lt;- data.frame(x1 = 10:15, x2 = 16:21, x3 = 22:27)
  vec; df
  
  # The desired result is the vector:
  c(10, 17, 24, 13, 20, 27)
  # 10 because for row 1, we are taking the value from column 1
  # 17 because for row 2, we are taking the value from column 2
  # 24 because for row 3, we are taking the value from column 3, etc.
  </code></pre>
  
  <p>One idea I had is to create a boolean matrix with the same dimensions as my data frame, somehow populate it with TRUEs based on the vector vec and then use that boolean matrix to subset the original data frame. But I am not sure how to do it without loops either!</p>
  
  <pre><code>bulmatr &lt;- matrix(rep(FALSE, nrow(df) * ncol(df)), nrow = nrow(df))
  bulmatr
  </code></pre>
  
  <p>Thank you very much!</p>