Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select multiple data columns in function

How can I select for multiple existing columns from a dataframe when I index my function with the triple dots as a parameter?

for example:

devTest <- function(data,...){
  col = list(...)
  innerTest <- function(...){
    more = list(...)
    data %>% select(more)
  }
  x <- innerTest({{col}})
  x
}
devTest(mtcars,mpg, gear)

produces this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error in devTest(mtcars, vs) : object ‘vs’ not found

>Solution :

The main issue is that you need to defuse the arguments using enquos (since you want to pass column symbols rather than strings to devText):

devTest <- function(data, ...) {
    col <- enquos(...)
    innerTest <- function(col) {
        data %>% select(!!!col)
    }
    innerTest(col)
}
devTest(mtcars,mpg, gear)

Other minor issues are the duplicate list(...) calls which are not necessary, as we can define innerTest to take a list of quosures directly (which we can then evaluate using the triple-bang operator !!!).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading