0

I have a wrapper function which uses dplyr::select(), however when I attempt to use it to select columns by name, it throws an object * not found error. I know it has something to do with the way select() uses quasiquotation but I don't know exactly why.

Here is my attempt using as_mapper:

fun1 = as_mapper(~select(.x, .y)) fun1(iris, Species) Error in .f(.x[[i]], ...) : object 'Species' not found 

Using base function notation:

fun2 = function(dat, x) {select(substitute(dat), substitute(x))} fun2(iris, Species:Sepal.Length) Error in UseMethod("select_") : no applicable method for 'select_' applied to an object of class "name" 

I would be grateful if someone could shed some light on why these errors are occurring.

3
  • as_mapper expects a character vector (or numeric for number-based indexing). Calling fun1(iris, "Species") or fun1(iris, 5) works, but not when Species is supplied as a name of an object (that might not exist in the environment). Commented Nov 7, 2019 at 5:21
  • True but why doesn't substitute() fix that? Commented Nov 7, 2019 at 5:26
  • 1
    With the latest version of dplyr you would use fun3 = function(dat, x) {select({{dat}}, {{x}})}; fun3(iris, Species:Sepal.Length). The problem with substitute is it happens too late. The problem with as_mapper is it doesn't support non-standard evaluation. Commented Nov 7, 2019 at 5:32

1 Answer 1

1

I believe this is related to non-standard evaluation (NSE) in R. Why dont you try using rlang to work with dplyr functions, as referenced here.

library(magrittr) fun2 <- function(dat, x) { x <- rlang::enquo(x) dplyr::select(dat,!!x) } fun2(iris, Species:Sepal.Length) %>% tibble::tibble() # A tibble: 150 x 1 .$Species $Petal.Width $Petal.Length $Sepal.Width $Sepal.Length <fct> <dbl> <dbl> <dbl> <dbl> 1 setosa 0.2 1.4 3.5 5.1 2 setosa 0.2 1.4 3 4.9 3 setosa 0.2 1.3 3.2 4.7 4 setosa 0.2 1.5 3.1 4.6 5 setosa 0.2 1.4 3.6 5 6 setosa 0.4 1.7 3.9 5.4 7 setosa 0.3 1.4 3.4 4.6 8 setosa 0.2 1.5 3.4 5 9 setosa 0.2 1.4 2.9 4.4 10 setosa 0.1 1.5 3.1 4.9 # ... with 140 more rows 

I would also like to point out that @MrFlick is also correct and the new interpolation method through the curly-curly operator is a nice shortcut

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.