Programming with dplyr and lazyeval Programming with dplyr and lazyeval r r

Programming with dplyr and lazyeval


One option may be to make write select_happy almost the same way as the standard select function:

select_happy<- function(df, ...){  select_(df, .dots = setNames(lazy_dots(...), "happy"))}f <- function(){  print('foo')}> select_happy(df, a)  happy1     12     23     3> > select_happy(df, f)  happy1     42     53     6> > select_happy(df, lm)  happy1     72     83     9

Note that the function definition of the standard select function is:

> selectfunction (.data, ...) {    select_(.data, .dots = lazyeval::lazy_dots(...))}<environment: namespace:dplyr>

Also note that by this definition, select_happy accepts multiple columns to be selected, but will name any additional columns "NA":

> select_happy(df, lm, a)  happy NA1     7  12     8  23     9  3

Of course you could make some modifications for such cases, for example:

select_happy<- function(df, ...){  dots <- lazy_dots(...)  n <- length(dots)  if(n == 1) newnames <- "happy" else newnames <- paste0("happy", seq_len(n))  select_(df, .dots = setNames(dots, newnames))}> select_happy(df, f)  happy1     42     53     6> select_happy(df, lm, a)  happy1 happy21      7      12      8      23      9      3