title: In R: subset or dplyr::filter with variable from vector
body: <pre><code>df &lt;- 
    data.frame(a=LETTERS[1:4],
               b=rnorm(4)
               )
  
  vals &lt;- c("B","D")
  </code></pre>
  
  <p>I can filter/subset <code>df</code> with values in <code>val</code> with:</p>
  
  <pre><code>dplyr::filter(df, a %in% vals)
  subset(df, a %in% vals)
  </code></pre>
  
  <p>Both gives:</p>
  
  <pre><code>  a         b
  2 B 0.4481627
  4 D 0.2916513
  </code></pre>
  
  <p>What if I have a variable name in a vector, e.g.:</p>
  
  <pre><code>&gt; names(df)[1]
  [1] "a"
  </code></pre>
  
  <p>Then it doesnt work - I guess because its quoted</p>
  
  <pre><code>dplyr::filter(df, names(df)[1] %in% vals)
  [1] a b
  &lt;0 rows&gt; (or 0-length row.names)
  </code></pre>
  
  <p>How do you do this ?</p>
  
  <p><strong>UPDATE ( what if its dplyr::tbl_df(df) )</strong></p>
  
  <p>Answers below work fine for data.frames, but not for dplyr::tbl_df wrapped data:</p>
  
  <pre><code>df&lt;-dplyr::tbl_df(df)
  dplyr::filter(df, df[,names(df)[1]] %in% vals)
  </code></pre>
  
  <p>Does not work (I thought <code>tbl_df</code> was a simple wrap on top of df ? )</p>
  
  <p>This does work again: </p>
  
  <pre><code>dplyr::filter(df, as.data.frame(df)[,names(df)[1]] %in% vals)
  </code></pre>
  
  <p><strong>FINAL UPDATE: It works with tbl_df() using lazyeval::interp</strong></p>
  
  <p>See AndreyAkinshin's solution below.</p>