Home > OS >  Select multiple data columns in function
Select multiple data columns in function

Time:10-09

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:

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

CodePudding user response:

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 !!!).

  •  Tags:  
  • r
  • Related