4

Question

How would I do the following using quosures?

library(tidyverse)
lkp <- c("am", "vs", "Sepal.Width", "Sepal.Length")
stringSelect <- function(mdat) {
   lkpOK <- intersect(lkp, names(mdat))
   mdat %>% select(one_of(lkpOK))
}
stringSelect(mtcars)
stringSelect(iris)

So basically, how can I subset lkpq below to achieve the same thing with quos to avoid the warning?

lkpq <- quos(am, vs, Sepal.Width, Sepal.Length)
quosSelect <- function(mdat) {
   lkpqOK <- lkpq ##???
   mdat %>% select(!!!lkpqOK)
}
quosSelect(mtcars) ## does not work
quosSelect(iris)

Context

In my application I am mixing traditional R selectors and tidyverse verbs but I want to stick to one system for consistency. Most of the things are easy to translate from one "universe" to another but I am struggling with this bit.


Footnote

I know that there are plenty possibilities to solve that. But for the sake of my learning let's assume that lkpq is fixed and cannot be changed. So I am really interested to learn how I could use a list of quosures with select if some of the elements are not part of the underlying data.

thothal
  • 16,690
  • 3
  • 36
  • 71

1 Answers1

2

We can use

quosSelect <- function(mdat) {

  nm1 <- intersect(names(mdat), sapply(lkpq, quo_name))
  mdat %>% 
          select(nm1)
  }

quosSelect(mtcars) 
quosSelect(iris)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Ok, transfroming the quosure back to a string is of course a valid solution +1. Feels a bit hackish though. Or is my problem not meant for `quo`? – thothal Jul 03 '18 at 12:42
  • 1
    @thothal You said the solution works with a warning. But, I am not able to make it work. I used `dplyr_0.7.5` and `rlang_0.2.1` What are the versions of packages you have – akrun Jul 03 '18 at 13:03
  • Hmm, funny, starting from a fresh session, I also get an error. Now no clue, why it worked in between. I will update my post. thanks. – thothal Jul 03 '18 at 13:22
  • @thothal it may be due to some variables that you created in the earlier session. No idea about that – akrun Jul 03 '18 at 14:08