Reputation: 2072
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.
Upvotes: 0
Views: 92
Reputation: 1423
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
Upvotes: 1