ddl
ddl

Reputation: 13

How to use arrange_ in my function?

Basically my problem is I don't understand how to assign multiple variable names as a "comma separated list" for my own function. My function is written as below:

tsf <- function(df, ...){
    df<- arrange_(df, .dots = substitute(...))
    other stuff
  return(df)
}

but if I use it as

t <- tsf(df, var1, var2)

the dataframe will only be arranged on the basis of var1, instead of as in arrange(df, var1, var2) which it will be arranged by both.

How should I correct my code?

Upvotes: 1

Views: 85

Answers (2)

Benjamin
Benjamin

Reputation: 17279

You can use alist to capture the values of the dots arguments in a list.

tsf <- function(df, ...){
  dots <- eval(substitute(alist(...)))
  dots <- vapply(dots,
                 deparse,
                 character(1))
  df <- dplyr::arrange_(df, .dots = dots)
  return(df)
}

tsf(mtcars, am, carb, gear)

See the section on "Capturing unevaluated …" at http://adv-r.had.co.nz/Computing-on-the-language.html

Upvotes: 2

lukeA
lukeA

Reputation: 54287

See the vignette:

library(dplyr)
packageVersion("dplyr")
# [1] ‘0.5.0.9004’
tsf <- function(df, ...){
  df<- arrange(df, !!!quos(...))
  return(df)
}
tsf(mtcars, vs, cyl)

Also note

that the underscored version of each main verb (filter_(), select_() etc). is no longer needed, and so these functions have been deprecated (but remain around for backward compatibility).

Upvotes: 2

Related Questions