rdplyrnon-standard-evaluationstandard-evaluation

Standard evaluation and non-standard evaluation in R


I am confused about dplyr functions' arguments and not quite clear about standard evalution (SE) or non-standard evaluation (NSE). I just want to pass a variable to dplyr::arrange() but it failed. However, passing to dplyr::select() works.

> library(dplyr)
> library(magrittr)
> var_name <- "mpg"
> mtcars %>% as_tibble() %>% dplyr::select(var_name)
# A tibble: 32 x 1
 mpg
 * <dbl>
 1  21.0
 2  21.0
 3  22.8
 4  21.4
 5  18.7
 6  18.1
 7  14.3
 8  24.4
 9  22.8
10  19.2
# ... with 22 more rows
> mtcars %>% as_tibble() %>% dplyr::arrange(var_name)
Error in arrange_impl(.data, dots) : 
  incorrect size (1) at position 1, expecting : 32

I searched a solution using SE version and it works:

> mtcars %>% as_tibble() %>% dplyr::arrange_(var_name)

Why dplyr::select() differs from dplyr::arrange() in NSE?

How to fix the error below in global environment?

> as_tibble(mtcars) %>% dplyr::mutate(paste0(var_name,"_Minus1") = mtcars$mpg - 1)
Error: unexpected '=' in "as_tibble(mtcars) %>% dplyr::mutate(paste0(var_name,"_Minus1") ="

Thanks!


Solution

  • We can use arrange_at which takes objects

    mtcars %>%
       as_tibble() %>%
       dplyr::arrange_at(var_name)
    

    Or another option is to convert to symbol with sym from rlang and evaluate with !!

    mtcars %>%
       as_tibble() %>%
       dplyr::arrange(!! rlang::sym(var_name))